<template>
  <div class="app-container" style="height: calc(100vh - 84px); display: flex;">
    <!-- 左侧合同列表 -->
    <div class="left-panel" style="width: 30%; border-right: 1px solid #e4e7ed; overflow-y: auto;">
      <ContractList ref="contractList"
        @add="handleAdd" @update="handleUpdate" @delete="handleDelete" @export="handleExport"
        @exportContract="handleExportContract" @rowClick="handleRowClick" />
    </div>

    <!-- 右侧内容区域 -->
    <div class="right-panel" v-if="form.contractId" style="flex: 1; display: flex; flex-direction: column;">
      <!-- 右侧上方：合同内容信息预览 -->
      <div class="preview-panel" ref="previewPanel"
        style="flex: 1; overflow-y: auto; border-bottom: 1px solid #e4e7ed;">
        <ContractPreview :contract="form" @updateStatus="handleStatusChange" />
      </div>

      <!-- 拖拽调整条 -->
      <div class="resize-handle" ref="resizeHandle"
        style="height: 8px; background-color: #f5f7fa; cursor: row-resize; display: flex; align-items: center; justify-content: center;"
        @mousedown="startResize">
        <div style="width: 40px; height: 2px; background-color: #dcdfe6;"></div>
      </div>

      <!-- 右侧下方：Tab标签页 -->
      <div class="tab-panel" ref="tabPanel" style="flex: 1; overflow-y: auto;">
        <ContractTabs :contractId="form.contractId" :financeList="financeList" :objectionList="objectionList"
          :coilList="coilList" :tabLoading="tabLoading" />
      </div>
    </div>
    <div v-else style="flex: 1; display: flex; flex-direction: column;">
      <el-empty description="选择合同后查看内容" />
    </div>

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 前四个字段占一排 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签订时间" prop="signTime">
              <el-date-picker clearable v-model="form.signTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择签订时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker clearable v-model="form.deliveryDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择交货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订地点" prop="signLocation">
              <el-input v-model="form.signLocation" placeholder="请输入签订地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品内容">
          <editor v-model="form.productContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="合同内容">
          <editor v-model="form.contractContent" :min-height="192" />
        </el-form-item>

        <!-- 供方和需方左右布局 -->
        <el-row :gutter="20">
          <!-- 供方信息 -->
          <el-col :span="12">
            <el-form-item label="供方" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供方" />
            </el-form-item>
            <el-form-item label="供方地址" prop="supplierAddress">
              <el-input v-model="form.supplierAddress" placeholder="请输入供方地址" />
            </el-form-item>
            <el-form-item label="供方电话" prop="supplierPhone">
              <el-input v-model="form.supplierPhone" placeholder="请输入供方电话" />
            </el-form-item>
            <el-form-item label="供方开户行" prop="supplierBank">
              <el-input v-model="form.supplierBank" placeholder="请输入供方开户行" />
            </el-form-item>
            <el-form-item label="供方账号" prop="supplierAccount">
              <el-input v-model="form.supplierAccount" placeholder="请输入供方账号" />
            </el-form-item>
            <el-form-item label="供方税号" prop="supplierTaxNo">
              <el-input v-model="form.supplierTaxNo" placeholder="请输入供方税号" />
            </el-form-item>
          </el-col>

          <!-- 需方信息 -->
          <el-col :span="12">
            <el-form-item label="需方" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入需方" />
            </el-form-item>
            <el-form-item label="需方地址" prop="customerAddress">
              <el-input v-model="form.customerAddress" placeholder="请输入需方地址" />
            </el-form-item>
            <el-form-item label="需方电话" prop="customerPhone">
              <el-input v-model="form.customerPhone" placeholder="请输入需方电话" />
            </el-form-item>
            <el-form-item label="需方开户行" prop="customerBank">
              <el-input v-model="form.customerBank" placeholder="请输入需方开户行" />
            </el-form-item>
            <el-form-item label="需方账号" prop="customerAccount">
              <el-input v-model="form.customerAccount" placeholder="请输入需方账号" />
            </el-form-item>
            <el-form-item label="需方税号" prop="customerTaxNo">
              <el-input v-model="form.customerTaxNo" placeholder="请输入需方税号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 最下方的附件和备注等信息保持原样 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="技术附件" prop="techAnnex">
          <file-upload v-model="form.techAnnex" :fileType="['pdf', 'jpeg', 'jpg', 'png', 'webp']"></file-upload>
        </el-form-item>
        <el-form-item label="商务附件" prop="businessAnnex">
          <file-upload v-model="form.businessAnnex" :fileType="['pdf', 'jpeg', 'jpg', 'png', 'webp']"></file-upload>
        </el-form-item>
        <el-form-item label="排产函" prop="productionSchedule">
          <file-upload v-model="form.productionSchedule"
            :fileType="['pdf', 'jpeg', 'jpg', 'png', 'webp']"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getContract, delContract, addContract, updateContract, listContractOrderObjection, listContractPackaging } from "@/api/crm/contract";
import ContractList from "./components/ContractList.vue";
import ContractPreview from "./components/ContractPreview.vue";
import ContractTabs from "./components/ContractTabs.vue";

export default {
  name: "Contract",
  components: {
    ContractList,
    ContractPreview,
    ContractTabs
  },
  data() {
    return {
      financeList: [],
      objectionList: [],
      coilList: [],
      loading: false,
      tabLoading: false,
      // 按钮loading
      buttonLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: undefined,
        contractNo: undefined,
        supplier: undefined,
        customer: undefined,
        signTime: undefined,
        deliveryDate: undefined,
        signLocation: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractId: [
          { required: true, message: "合同主键ID不能为空", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        contractNo: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
        supplier: [
          { required: true, message: "供方不能为空", trigger: "blur" }
        ],
        customer: [
          { required: true, message: "需方不能为空", trigger: "blur" }
        ],
        signTime: [
          { required: true, message: "签订时间不能为空", trigger: "blur" }
        ],
        deliveryDate: [
          { required: true, message: "交货日期不能为空", trigger: "blur" }
        ],
        signLocation: [
          { required: true, message: "签订地点不能为空", trigger: "blur" }
        ],
        productContent: [
          { required: true, message: "产品内容不能为空", trigger: "blur" }
        ],
        contractContent: [
          { required: true, message: "合同内容不能为空", trigger: "blur" }
        ],
        supplierAddress: [
          { required: true, message: "供方地址不能为空", trigger: "blur" }
        ],
        supplierPhone: [
          { required: true, message: "供方电话不能为空", trigger: "blur" }
        ],
        supplierBank: [
          { required: true, message: "供方开户行不能为空", trigger: "blur" }
        ],
        supplierAccount: [
          { required: true, message: "供方账号不能为空", trigger: "blur" }
        ],
        supplierTaxNo: [
          { required: true, message: "供方税号不能为空", trigger: "blur" }
        ],
        customerAddress: [
          { required: true, message: "需方地址不能为空", trigger: "blur" }
        ],
        customerPhone: [
          { required: true, message: "需方电话不能为空", trigger: "blur" }
        ],
        customerBank: [
          { required: true, message: "需方开户行不能为空", trigger: "blur" }
        ],
        customerAccount: [
          { required: true, message: "需方账号不能为空", trigger: "blur" }
        ],
        customerTaxNo: [
          { required: true, message: "需方税号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "合同状态不能为空", trigger: "change" }
        ],
      }
    };
  },

  methods: {

    /** 处理合同状态更新 */
    handleStatusChange(status) {
      this.form.status = status;
      updateContract({
        ...this.form,
        status: status
      }).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '合同状态更新成功',
            type: 'success'
          });
        }
      })
      this.$refs.contractList.getList();
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 行点击事件 */
    handleRowClick(row) {
      this.form = row;
      this.tabLoading = true;
      this.getCoilList();
      listContractOrderObjection(row.contractId).then(response => {
        this.financeList = response.data.financeList || [];
        this.objectionList = response.data.oobjectionList || [];
      }).finally(() => {
        this.tabLoading = false;
      })
    },
    /** 查询合同配卷列表 */
    getCoilList() {
      listContractPackaging(this.form.contractId).then(response => {
        this.coilList = response.data || [];
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        contractId: undefined,
        contractName: undefined,
        contractNo: undefined,
        supplier: undefined,
        customer: undefined,
        signTime: undefined,
        deliveryDate: undefined,
        signLocation: undefined,
        productContent: undefined,
        contractContent: undefined,
        supplierAddress: undefined,
        supplierPhone: undefined,
        supplierBank: undefined,
        supplierAccount: undefined,
        supplierTaxNo: undefined,
        customerAddress: undefined,
        customerPhone: undefined,
        customerBank: undefined,
        customerAccount: undefined,
        customerTaxNo: undefined,
        techAnnex: undefined,
        businessAnnex: undefined,
        productionSchedule: undefined,
        status: 0,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const contractId = row.contractId || this.ids
      getContract(contractId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$refs.contractList.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$refs.contractList.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同信息编号为"' + contractIds + '"的数据项？').then(() => {
        return delContract(contractIds);
      }).then(() => {
        this.$refs.contractList.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    },
    /** 导出合同操作 */
    handleExportContract(row) {
      // 合同导出
    },
    /** 开始拖拽调整 */
    startResize(e) {
      e.preventDefault();
      const previewPanel = this.$refs.previewPanel;
      const tabPanel = this.$refs.tabPanel;
      const startY = e.clientY;
      const startPreviewHeight = previewPanel.offsetHeight;
      const parentHeight = previewPanel.parentElement.offsetHeight;

      const handleMouseMove = (event) => {
        const deltaY = event.clientY - startY;
        const newPreviewHeight = startPreviewHeight + deltaY;
        const newTabHeight = parentHeight - newPreviewHeight - 8; // 8是拖拽条的高度

        if (newPreviewHeight > 100 && newTabHeight > 100) { // 最小高度限制
          previewPanel.style.flex = `0 0 ${newPreviewHeight}px`;
          tabPanel.style.flex = `0 0 ${newTabHeight}px`;
        }
      };

      const handleMouseUp = () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };

      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }
  }
};
</script>


<style scoped>
.app-container {
  overflow: hidden;
  padding: 0;
}

.left-panel {
  height: calc(100vh - 84px);
  box-sizing: border-box;
  overflow-y: auto;
}

.right-panel {
  height: calc(100vh - 84px);
  overflow: hidden;
}

.preview-panel {
  overflow-y: auto;
}

.tab-panel {
  overflow-y: auto;
}
</style>