<template>
  <div style="
      background-color: #fafafa;
      height: calc(100vh - 80px);
      overflow-y: auto;
    ">
    <el-button type="primary" @click="openFullScreen1" v-loading.fullscreen.lock="fullscreenLoading"
      style="position: absolute; top: -100px">
    </el-button>
    <div style="
        position: fixed;
        background-color: #fafafa;
        z-index: 999;
        width: 100%;
        padding: 0 12px 8px 0;
        right: 0;
        display: flex;
        justify-content: flex-end;
      ">
      <el-button size="small" icon="el-icon-check" @click="save" type="primary">暂存</el-button>
      <el-button size="small" icon="el-icon-coordinate" type="primary" @click="save('true')">提交审核</el-button>
    </div>
    <div class="pointOut" v-show="addEditChange == '新增合同'">
      <el-dialog v-loading="typeLoading" title="选择合同模板" :append-to-body="true" :visible.sync="dialogVisible"
        :close-on-press-escape="false" @close="contractPopup" width="45%" style="text-align: right">
        <div style="display: flex; justify-content: space-around">
          <el-button plain @click="selectContract(item)" v-for="(item, index) in agreementList" :key="index">
            {{ item.ddd_DicDetailsName }}</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-if="dialogVisible"></div>
    <div v-else>
      <el-collapse v-model="activeNames" @change="handleChange(activeNames, 1)" class="box">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">基本信息</span>
              <span class="operate">{{ arr1 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <base-form ref="customForm" :formRow="topFormRow" :isFunBtn="isFunBtn" @onSelect="getFromSelect"
            :spanNumber="spanNumber" @elDialogClick="elDialogClick" style="padding: 10px 0" justifyContent="flex-end"
            :rules="rules" @dataChanges="dataChanges">
          </base-form>
        </el-collapse-item>
        <!-- <el-collapse-item name="2">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">关联合同</span>
              <span class="operate">{{ arr2 == -1 ? "展开" : "关闭" }}</span>
            </div>
          </template>
          <base-form ref="moneyCustomForm" :formRow="relatedContract" :isFunBtn="isFunBtn" @onSelect="getFromSelect"
            :spanNumber="spanNumber" @elDialogClick="elDialogClick" style="padding: 10px 0" justifyContent="flex-end">
          </base-form>
        </el-collapse-item> -->
        <el-collapse-item name="3">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">保证金、质保金</span>
              <span class="operate">{{ arr3 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <base-form ref="bond" :formRow="secondFormRow" :isFunBtn="isFunBtn" @onSelect="getFromSelect"
            :spanNumber="spanNumber" @elDialogClick="elDialogClick" style="padding: 10px 0" justifyContent="flex-end">
          </base-form>
        </el-collapse-item>
        <el-collapse-item name="4">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">合同明细({{ detailedList.length }})</span>
              <span class="operate">{{ arr4 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <el-button type="primary" plain @click="agreementAdd" v-if="detailedList.length == '0'" icon="el-icon-plus"
            circle style="
              position: absolute;
              top: 54px;
              left: 14px;
              z-index: 999;
              padding: 6px;
            "></el-button>
          <equipment-details ref="equipmentDetails"></equipment-details>
        </el-collapse-item>
        <el-collapse-item name="5">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">执行阶段/收款约定({{ stageList.length }})</span>
              <span class="operate">{{ arr5 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <el-button type="primary" plain @click="stageAdd" v-if="stageList.length == '0'" icon="el-icon-plus" circle
            style="
              position: absolute;
              top: 54px;
              left: 14px;
              z-index: 999;
              padding: 6px;
            "></el-button>
          <contract-stage ref="contractStage"></contract-stage>
        </el-collapse-item>
        <el-collapse-item name="6">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">附件管理</span>
              <span class="operate">{{ arr6 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <attachment-management ref="appendix"></attachment-management>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 部门+对外签订弹窗 -->
    <base-organization ref="baseOrganization" :menuData="organMenuData"
      @handleConfirmClick="organizationHandleConfirm"></base-organization>

    <!-- 项目名称弹窗 -->
    <base-dialog :closeEscape="true" :showClose="true" :closeModal="false" @handleConfirmClick="choiceHandleConfirm"
      :dialogVisible.sync="choiceDialog" class="userDialog" :title="choiceTitle" width="90%" top="10vh"
      :footerShow="true">
      <base-choice @onQuery="supplierPage" :tableColumn="tableColumn" :tableData="choiceTableData"
        @getTableList="getTableList" @handleNodeClick="treeClick" ref="choice" :choiceDialog="choiceDialog"
        :menuData="itemTree" v-loading="itemLoading"></base-choice>
    </base-dialog>
    <!-- 客户名称、供方单位弹窗 -->
    <base-dialog :closeEscape="true" :showClose="true" :closeModal="false" @handleConfirmClick="choiceSupplier"
      @close="close" :dialogVisible.sync="supplierUnit" class="userDialog" :title="choiceTitle" width="90%" top="10vh"
      :footerShow="true">
      <div style="display: flex; margin: 10px 0 0 10px" v-if="choiceTitle != '所属业务员'">
        <el-input v-model="queryCriteria" clearable placeholder="请输入客户编码或名称"
          style="width: 220px; margin-right: 10px"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="queryClick">查询</el-button>
      </div>
      <div class="connection">
        <base-choice @onQuery="supplierPage" :tableColumn="supplierTableColumn" :tableData="supplierTableData"
          @getTableList="getTableList" @handleNodeClick="classifyTree" ref="supplier" :choiceDialog="choiceDialog"
          v-loading="connectionLoading" :menuData="itemTree1"></base-choice>
      </div>
    </base-dialog>
    <base-radio-people ref="baseRadioPeople" @personConfirmClick="personConfirmClick"></base-radio-people>
  </div>
</template>

<script>
import baseForm from "@/components/base/baseNewForm/index.vue";
import baseDialog from "@/components/base/BaseNewDialog/index.vue";
import baseLayout from "@/components/base/baseLayout";
import baseTree from "@/components/base/BaseMenuTree/index.vue";
import baseChoice from "@/components/base/baseChoice/index.vue";
import equipmentDetails from "./equipmentDetails.vue";
import contractStage from "./contractStage.vue";
import lookForm from "@/components/base/baselookForm/index.vue";
import attachmentManagement from "./attachmentManagement.vue";
import baseOrganization from "@/components/base/baseOrganization/index.vue";
import configData from "./configData";
import baseRadioPeople from "@/components/base/baseRadioPeople/index.vue";
import { getCompanyId } from "@/utils/auth";
import {
  GetOrganTree,
  OrganGetSupplier,
  OrganGetCustomer,
  connectionTree,
  OrganGetProject,
  projectDetails,
  OrganGetUser,
  OrganSaveContract,
  ProjectClassification,
} from "@/api/apis/organization";
import { dataDictionaryGetBillList } from "@/api/apis/dataDictionary";
import { getContractDetails } from "@/api/apis/contract";
import {
  getAuditBtn,
  getAuditNote,
  audit,
  submitAudit,
} from "@/api/apis/audit";
export default {
  name: "AddEditChange",
  components: {
    baseForm,
    baseTree,
    baseDialog,
    baseLayout,
    baseChoice,
    equipmentDetails,
    contractStage,
    attachmentManagement,
    baseOrganization,
    baseRadioPeople,
  },
  data() {
    return {
      tableColumn: {},
      supplierTableColumn: [], // 供方表头
      supplierTableData: [], // 供方表体
      mainHight: "calc(100% - 39px)",
      mainColor: "#f8f8f8 ",
      choiceTitle: "",
      activeName: "first",
      topFormRow: configData.topFormRow,
      secondFormRow: configData.secondFormRow,
      // relatedContract: configData.relatedContract,
      isFunBtn: false,
      spanNumber: 6,
      organizationDialog: false, //选择组织机构弹窗
      choiceDialog: false, //选择组织机构弹窗
      supplierUnit: false, // 供方单位弹窗
      organMenuData: [],
      organizationForm: {},
      treeHight: "350px",
      propLabel: "",
      choiceTableData: [],
      pageModel: {
        page: 1, //当前页码
        limit: 10, //每页显示多少
        cusClassify: "", //树形分类id
        Sequence: "", //排列方式
        SequenceName: "", //需要排列的字段名
        CodeOrName: "",
      },
      organization: "",
      dropList1: [],
      dropList2: [],
      dropList3: [],
      itemTree: [],
      itemTree1: [],
      itemLoading: false,
      connectionLoading: false,
      activeNames: ["1"],
      flex: "flex-end",
      dialogVisible: false,
      agreementList: [],
      arr1: "",
      arr2: "-1",
      arr3: "-1",
      arr4: "-1",
      arr5: "-1",
      arr6: "-1",
      itemId: "",
      typeLoading: false,
      detailedList: [],
      stageList: [],
      queryCriteria: "",
      billID: "",
      rules: configData.formVerification,
      switch: false,
      notSelected: false,
      clickSave: false,
      addEditChange: null,
      queryId: null,
      testForm: null,
      fullscreenLoading: false,
      firstOpen: true,
      refresh: true,
    };
  },
  watch: {
    detailedList: {
      deep: true,
      handler(newVal, oldVal) {
        let num = 0;
        newVal.forEach((el) => {
          num = Number(num) + Number((el.quantity * el.unitPrice).toFixed(2));
        });
        this.$refs.customForm.getField("oriTaxMoney", num.toFixed(2));
        let nums = 0;
        if (this.$refs.customForm.ruleForm.exchangeRate != undefined) {
          newVal.forEach((el) => {
            nums =
              Number(nums) +
              Number(
                (
                  el.money -
                  (el.money * this.$refs.customForm.ruleForm.exchangeRate) / 100
                ).toFixed(2)
              );
          });
          this.$refs.customForm.getField("taxMoney", nums.toFixed(2));
        }
      },
    },
    exchangeRate1: {
      handler(newVal, oldVal) {
        let num = 0;
        num =
          (this.$refs.customForm.ruleForm.oriTaxMoney * (100 - newVal)) / 100;
        if (num != 0) {
          this.$refs.customForm.getField("taxMoney", num.toFixed(2));
        }
      },
    },
    testForm: {
      deep: true,
      handler(newVal, oldVal) {
        let num = 0;
        num =
          (this.$refs.customForm.ruleForm.oriTaxMoney *
            (100 - newVal.exchangeRate)) /
          100;
        this.$refs.customForm.getField("taxMoney", num.toFixed(2));
      },
    },
  },
  activated() {
    if (this.$route.query.Refresh == "true") {
      this.refresh = true;
    }
    if (this.firstOpen == false && this.refresh == true) {
      this.$tab.refreshPage(this.$route);
    }
    this.firstOpen = false;
    this.$route.query.Refresh = false;
  },
  computed: {
    detailedList1() {
      if (this.switch) {
        return JSON.parse(
          JSON.stringify(this.$refs.equipmentDetails.tableData)
        );
      }
    },
    exchangeRate1() {
      if (this.switch) {
        return this.$refs.customForm.ruleForm.exchangeRate;
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    //to是当前页面,from是从哪里来,next是放行
    next((vm) => {
      if (to.query.name) {
        vm.$set(to.meta, "title", to.query.name);
        // to.meta.title = to.query.name //获取从上个页面传过来的name再进行修改
      }
    }); //切记操作完一定要记得放行,否则无法正常跳转页面
  },
  mounted() {
    this.inPage();
  },
  methods: {
    // 页面初始化
    inPage() {
      this.addEditChange = this.$route.query.name;
      if (this.addEditChange == null || this.addEditChange == "新增合同") {
        this.dialogVisible = true;
      }
      if (this.addEditChange == "变更合同") {
        const data = {
          elCol: [
            {
              label: "变更原因",
              prop: "changeContent",
              tag: "elInput",
              span: 24,
            },
          ],
        };
        this.topFormRow.splice(6, 0, data);
      }
      this.getMenuData();
      this.getContractList();
      this.getInvoiceList();
      this.getCurrencyList();
      this.OrganGetProject();
      if (
        this.addEditChange &&
        (this.addEditChange == "新增合同（复制）" ||
          this.addEditChange == "编辑合同" ||
          this.addEditChange == "变更合同")
      ) {
        this.init();
      }
      this.refresh = false;
      this.$route.query.Refresh = false;
    },
    init() {
      this.queryId = this.$route.query.id;
      this.detailedData();
      this.openFullScreen1();
      this.testForm = this.$refs.customForm.ruleForm;
      this.$refs.customForm.ruleForm.createPersonID = JSON.parse(
        localStorage.getItem("Admin-Info")
      ).personName;
    },
    openFullScreen1() {
      this.fullscreenLoading = true;
      setTimeout(() => {
        this.fullscreenLoading = false;
      }, 1200);
    },
    async detailedData() {
      const res = await getContractDetails({
        op: "edit",
        id: this.queryId,
      });
      if (res.success == "true") {
        this.editData = res.data[0];
        this.$refs.customForm.choiceAssignment(res.data[0]);
        // this.$refs.customForm.ruleForm = res.data[0];
        // this.$refs.moneyCustomForm.ruleForm = res.data[0];
        this.$refs.bond.ruleForm = res.data[0];
        if (this.addEditChange == "新增合同（复制）") {
          this.$refs.customForm.ruleForm.contractCode = null;
          res.data[1].forEach((el) => {
            el.detail_ID = null;
          });
          res.data[2].forEach((el) => {
            el.detail_ID = null;
          });
          res.data[3] = [];
        }
        this.$refs.equipmentDetails.tableData = res.data[1];
        this.$refs.contractStage.tableData = res.data[2];
        this.detailedList = res.data[1];
        this.stageList = res.data[2];
        this.$refs.appendix.UploadList1(res.data[3]);
        this.$refs.customForm.ruleForm.createPersonID = JSON.parse(
          localStorage.getItem("Admin-Info")
        ).personName;
      }
    },
    dataChanges() {
      if (this.clickSave) {
        this.$refs.customForm.$refs["ruleForm"].validate((valid) => {
          if (valid) {
          } else {
            return;
          }
        });
      }
    },
    contractPopup() {
      if (!this.notSelected) {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push("listContract");
      }
    },
    close() {
      this.queryCriteria = "";
      this.itemTree1 = [];
      this.supplierTableData = [];
      this.$refs.supplier.setPageTotal(0);
    },
    // 查询
    queryClick() {
      if (this.choiceTitle == "选择客商") {
        this.pageModel.CodeOrName = this.queryCriteria;
        this.OrganGetCustomer();
      } else if (this.choiceTitle == "供方单位") {
        this.pageModel.CodeOrName = this.queryCriteria;
        this.OrganGetSupplier();
      }
    },
    initialization() {
      this.detailedList = this.$refs.equipmentDetails.tableData;
      this.stageList = this.$refs.contractStage.tableData;
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var dates = date.getDate();
      let time = year + "-" + month + "-" + dates;
      this.$refs.customForm.ruleForm.createPersonID = JSON.parse(
        localStorage.getItem("Admin-Info")
      ).personName;
      this.$refs.customForm.getField("createDate", time);
    },
    stageAdd() {
      this.$refs.contractStage.add();
    },
    agreementAdd() {
      this.$refs.equipmentDetails.add();
    },
    handleChange(val, index) {
      this.arr1 = val.indexOf("1");
      this.arr2 = val.indexOf("2");
      this.arr3 = val.indexOf("3");
      this.arr4 = val.indexOf("4");
      this.arr5 = val.indexOf("5");
      this.arr6 = val.indexOf("6");
    },
    // 选择合同类型
    selectContract(item) {
      this.dialogVisible = false;
      this.notSelected = true;
      this.$nextTick(() => {
        this.$refs.customForm.getField("conTypeName", item.ddd_DicDetailsName);
        this.$refs.customForm.getField("conType", item.ddd_DicDetailsID);
        this.initialization();
        this.switch = true;
      });
    },
    // 获得组织树状图
    async getMenuData() {
      let params = {
        // CompanyID: 1
        companyID: this.$store.state.user.companyID
          ? this.$store.state.user.companyID
          : getCompanyId(),
      };

      let res = await GetOrganTree(params);

      this.organMenuData = JSON.parse(res.data[0]);
    },
    // 获取项目分类
    async OrganGetProject() {
      let res = await ProjectClassification({});
      if (res.code == 1) {
        this.itemTree = res.data[0];
      }
    },
    // 获取合同类型
    async getContractList() {
      this.typeLoading = true;
      let params = {
        KindId: 29,
        page: 1,
        limit: 999,
        Sequence: "",
        SequenceName: "",
      };
      let res = await dataDictionaryGetBillList(params);
      this.agreementList = res.data[1];
      if (res.code == 1) {
        let arrList = [];
        if (res.data[0] > 0) {
          res.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            arrList.push(arr);
          });
        }
        this.dropList1 = arrList;
      }
      this.typeLoading = false;
    },
    // 获取发票类型
    async getInvoiceList() {
      let params = {
        KindId: 15,
        page: 1,
        limit: 999,
        sequence: "",
        sequenceName: "",
      };
      let res = await dataDictionaryGetBillList(params);
      if (res.code == 1) {
        let arrList = [];
        if (res.data[0] > 0) {
          res.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            arrList.push(arr);
          });
        }
        this.dropList2 = arrList;
        configData.topFormRow[6].elCol[1].options = arrList;
      }
    },
    // 获取币种类型
    async getCurrencyList() {
      let params = {
        KindId: 30,
        page: 1,
        limit: 999,
        sequence: "",
        sequenceName: "",
      };
      let res = await dataDictionaryGetBillList(params);
      if (res.code == 1) {
        let arrList = [];
        if (res.data[0] > 0) {
          res.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            arrList.push(arr);
          });
        }
        this.dropList3 = arrList;
        configData.topFormRow[5].elCol[2].options = arrList;
      }
    },
    // 保存
    async save(item) {
      this.clickSave = true;
      this.$refs.customForm.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.submitTo(item);
        } else {
          this.$message({
            message: "请输入必填项",
            type: "warning",
          });
          return;
        }
      });
    },
    async submitTo(item) {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var dates = date.getDate();
      let time = year + "-" + month + "-" + dates;
      const customForm = this.$refs.customForm.ruleForm; // 基本信息
      // const moneyCustomForm = this.$refs.moneyCustomForm.ruleForm; // 关联合同
      const bond = this.$refs.bond.ruleForm; //保证金
      let conTypeName = {}; // 合同类型
      this.dropList1.forEach((el) => {
        if (el.value == customForm.ConType) {
          conTypeName = el;
        }
      });

      let currencyName = {}; //币种
      this.dropList3.forEach((el) => {
        if (el.value == customForm.currencyName) {
          currencyName = el;
        }
      });
      let invoiceName = {}; //发票类型
      this.dropList2.forEach((el) => {
        if (el.value == customForm.invoiceType) {
          invoiceName = el;
        }
      });
      // 判断是否有合同明细
      let contractDetails = JSON.parse(
        JSON.stringify(this.$refs.equipmentDetails.tableData)
      );
      for (let i = 0; i < contractDetails.length; i++) {
        if (contractDetails[i].invName == "") {
          this.$message({
            message: `请选择合同明细行${i + 1}设备`,
            type: "warning",
          });
          return;
        } else if (contractDetails[i].quantity == "") {
          this.$message({
            message: `请录入合同明细行${i + 1}数量`,
            type: "warning",
          });
          return;
        }
      }
      // 判断是否有执行阶段/收款约定
      let implementationPhase = this.$refs.contractStage.tableData;
      for (let i = 0; i < implementationPhase.length; i++) {
        if (
          !("phaseName" in implementationPhase[i]) ||
          implementationPhase[i].phaseName == ""
        ) {
          this.$message({
            message: `请选择执行阶段/收款约定行${i + 1}阶段`,
            type: "warning",
          });
          return;
        } else if (
          !("warininDays" in implementationPhase[i]) ||
          implementationPhase[i].warininDays == ""
        ) {
          this.$message({
            message: `请录入执行阶段/收款约定行${i + 1}预警天数`,
            type: "warning",
          });
          return;
        } else if (
          !("planDate" in implementationPhase[i]) ||
          implementationPhase[i].planDate == null
        ) {
          this.$message({
            message: `请录入执行阶段/收款约定行${i + 1}执行日期`,
            type: "warning",
          });
          return;
        }
      }
      const params = {
        saveType: "",
        op: "",
        dataMain: {},
        business_Contract_detail: [],
        business_Contract_Phase: [],
        attIDS: this.$refs.appendix.appendix.join(),
      };
      if (
        this.addEditChange == "编辑合同" ||
        this.addEditChange == "变更合同"
      ) {
        if (this.addEditChange == "编辑合同") {
          params.op = "edit";
        } else if (this.addEditChange == "变更合同") {
          params.op = "change";
        }
        params.dataMain = {
          billid: this.editData.billid,
          beginDay: customForm.beginDay,
          companyID: customForm.companyNameID,
          companyName: customForm.companyID,
          conName: customForm.conName,
          conType: customForm.conType,
          conTypeName: conTypeName.label,
          contractCode: this.editData.contractCode, // 合同号
          // correlationContractCode: moneyCustomForm.correlationContractCode,
          createDate: this.editData.createDate, // 创建日期
          createPersonID: this.editData.createPersonID, // 创建人
          currency: currencyName.value,
          cusName: customForm.cusName, // ..
          customerCode: customForm.customerCode, // ..
          endDay: customForm.endDay,
          exchangeRate: customForm.exchangeRate,
          exchangeRateName: this.editData.exchangeRateName,
          externalConNum: customForm.externalConNum,
          invoiceType: invoiceName.value,
          isdelete: this.editData.isdelete, // 是否删除
          orgainName: customForm.organName,
          organID: customForm.organID,
          // oriTaxEarnestMoney: moneyCustomForm.oriTaxEarnestMoney,
          oriTaxMoney: customForm.oriTaxMoney,
          // oriTaxRetentionMoney: moneyCustomForm.oriTaxRetentionMoney,
          projectCode: customForm.projectCode, //项目编号
          projectName: customForm.projectName,
          remark: customForm.remark,
          // retentionEndDate: moneyCustomForm.endDay,
          // retentionStartDate: moneyCustomForm.beginDay,
          salesman: customForm.salesman, // 所属业务员
          singleDay: customForm.singleDay,
          // taxEarnestMoney: moneyCustomForm.taxEarnestMoney,
          taxMoney: customForm.taxMoney,
          // taxRetentionMoney: moneyCustomForm.taxRetentionMoney,
          updateDate: customForm.createDate, // 修改时间
          updatePersonID: JSON.parse(localStorage.getItem("Admin-Info"))
            .personID, // 修改人
          // venName: moneyCustomForm.venName, // ...
          // vendorCode: moneyCustomForm.vendorCode, // ...
          // vendorMoney: moneyCustomForm.vendorMoney,
          versionNo: customForm.versionNo,
          // createDate: this.editData.createDate, //创建时间
          currencyName: currencyName.label,
          invoiceTypeName: invoiceName.label,
          customerContact: customForm.customerContact,
          customerPhone: customForm.customerPhone,
        };
      } else if (
        this.addEditChange == "新增合同" ||
        this.addEditChange == "新增合同（复制）"
      ) {
        params.dataMain = {
          billid: "00000000-0000-0000-0000-000000000000",
          beginDay: customForm.beginDay,
          companyID: customForm.companyNameID,
          companyName: customForm.companyName,
          conName: customForm.conName,
          conType: customForm.conType,
          conTypeName: customForm.conTypeName,
          contractCode: "", // 合同号
          // correlationContractCode: moneyCustomForm.correlationContractCode,
          createDate: customForm.createDate, // 创建日期
          createPersonID: JSON.parse(localStorage.getItem("Admin-Info"))
            .personID, // 创建人
          currency: currencyName.value,
          cusName: customForm.cusName, // ..
          customerCode: customForm.customerCode, // ..
          endDay: customForm.endDay,
          exchangeRate: customForm.exchangeRate,
          exchangeRateName: "",
          externalConNum: customForm.externalConNum,
          invoiceType: invoiceName.value,
          isdelete: "", // 是否删除
          orgainName: customForm.organName,
          organID: customForm.organID,
          oriTaxEarnestMoney: bond.oriTaxEarnestMoney,
          oriTaxMoney: customForm.oriTaxMoney,
          oriTaxRetentionMoney: bond.oriTaxRetentionMoney,
          projectCode: customForm.projectCode, //项目编号
          projectName: customForm.projectName,
          remark: customForm.remark,
          retentionEndDate: bond.endDay,
          retentionStartDate: bond.beginDay,
          salesman: customForm.salesman, // 所属业务员
          singleDay: customForm.singleDay,
          taxEarnestMoney: bond.taxEarnestMoney,
          taxMoney: customForm.taxMoney,
          taxRetentionMoney: bond.taxRetentionMoney,
          updateDate: "", // 修改时间
          updatePersonID: "", // 修改人
          // venName: moneyCustomForm.venName, // ...
          // vendorCode: moneyCustomForm.vendorCode, // ...
          // vendorMoney: moneyCustomForm.vendorMoney,
          versionNo: customForm.versionNo,
          // createDate: this.editData.createDate, //创建时间
          currencyName: currencyName.label,
          invoiceTypeName: invoiceName.label,
          customerContact: customForm.customerContact,
          customerPhone: customForm.customerPhone,
        };
      }
      let list3 = this.$refs.equipmentDetails.tableData.filter((item) => {
        return item.detail_ID;
      });
      let list4 = this.$refs.equipmentDetails.tableData.filter((item) => {
        return !item.detail_ID;
      });
      list4.forEach((item) => {
        params.business_Contract_detail.push({
          invStd: item.invStd,
          unitPrice: item.unitPrice,
          cEQCode: item.cEQCode,
          detail_ID: "00000000-0000-0000-0000-000000000000", //主键id
          detail_Remark: item.detail_Remark,
          detail_createDate: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
            .toJSON()
            .split("T")
            .join(" ")
            .substr(0, 19),
          detail_updateDate: "",
          invCode: item.invCode,
          invName: item.invName,
          isCustomMade: item.isCustomMade,
          isNewProduct: item.isNewProduct,
          mainID: "00000000-0000-0000-0000-000000000000", //主表id
          nUnitMoney: item.nUnitMoney, //无税金额
          nUnitPeice: item.nUnitPeice, //无税单价
          quantity: item.quantity,
          rowIndex: this.$refs.equipmentDetails.optionIndex + 1, //行号
          tax: item.tax,
          taxMoney: item.taxMoney, //税额
          unit: item.unit, //计量单位
          unitMoney: item.money,
        });
      });
      list3.forEach((item) => {
        params.business_Contract_detail.push({
          invStd: item.specification,
          unitPrice: item.unitPrice,
          cEQCode: item.cEQCode,
          detail_ID: item.detail_ID, //主键id
          detail_Remark: item.detail_Remark,
          detail_createDate: item.detail_createDate,
          detail_updateDate: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
            .toJSON()
            .split("T")
            .join(" ")
            .substr(0, 19),
          invCode: item.invCode,
          invName: item.invName,
          isCustomMade: item.isCustomMade,
          isNewProduct: item.isNewProduct,
          mainID: item.mainID, //主表id
          nUnitMoney: item.nUnitMoney, //无税金额
          nUnitPeice: item.nUnitPeice, //无税单价
          quantity: item.quantity,
          rowIndex: this.$refs.equipmentDetails.optionIndex + 1, //行号
          tax: item.tax,
          taxMoney: item.taxMoney, //税额
          unit: item.unit, //计量单位
          unitMoney: item.money,
        });
      });
      let list1 = this.$refs.contractStage.tableData.filter((item) => {
        return item.detail_ID;
      });
      let list2 = this.$refs.contractStage.tableData.filter((item) => {
        return !item.detail_ID;
      });
      list1.forEach((item) => {
        params.business_Contract_Phase.push({
          phaseContent: item.phaseContent,
          phaseID: item.phaseID,
          phaseName: item.phaseName,
          detail_ID: item.detail_ID, //主键id
          detail_createDate: item.detail_createDate,
          detail_updateDate: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
            .toJSON()
            .split("T")
            .join(" ")
            .substr(0, 19),
          execAmount: item.execAmount,
          execMoney: item.execMoney,
          mainID: item.mainID, //主表id
          planDate: item.planDate,
          rowIndex: this.$refs.contractStage.optionIndex + 1, // 行号,
          warininDays: item.warininDays,
        });
      });
      list2.forEach((item) => {
        params.business_Contract_Phase.push({
          phaseContent: item.phaseContent,
          phaseID: item.phaseID,
          phaseName: item.phaseName,
          detail_ID: "00000000-0000-0000-0000-000000000000", //主键id
          detail_createDate: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
            .toJSON()
            .split("T")
            .join(" ")
            .substr(0, 19),
          detail_updateDate: "",
          execAmount: item.execAmount,
          execMoney: item.execMoney,
          mainID: "00000000-0000-0000-0000-000000000000", //主表id
          planDate: item.planDate,
          rowIndex: this.$refs.contractStage.optionIndex + 1, // 行号,
          warininDays: item.warininDays,
        });
      });
      // return console.log(params);
      const res = await OrganSaveContract(params);
      if (res.success == "true") {
        this.billID = res.data[0];
      }
      if (res.success == "true" && item == "true") {
        const obj = await submitAudit({
          billID: this.billID, //单据ID
          wfID: "2", //流程ID
          billKindID: "45", //单据类型ID
        });
        if (obj.success == "true") {
          this.$message({
            message: "提交审核成功",
            type: "success",
          });
          this.$router.push({
            path: "seeContract",
            query: {
              id: this.billID,
              Refresh: true,
            },
          });
          this.$store.dispatch("tagsView/delView", this.$route);
        }
      } else {
        if (res.success == "true") {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$router.push({
            path: "seeContract",
            query: {
              id: this.billID,
              Refresh: true,
            },
          });
          this.$store.dispatch("tagsView/delView", this.$route);
        }
      }
    },
    // 树点击事件
    treeClick(item) {
      // this.$refs.choice.optionData = ''
      // this.$refs.choice.radio = false
      this.projectDetails(item.id);
    },
    // 分类树点击
    classifyTree(item) {
      if (this.choiceTitle == "选择客商") {
        this.pageModel.cusClassify = item.id;
        this.pageModel.codeOrName = this.queryCriteria;
        this.OrganGetCustomer();
      } else if (this.choiceTitle == "供方单位") {
        this.pageModel.cusClassify = item.id;
        this.pageModel.CodeOrName = this.queryCriteria;
        this.OrganGetSupplier();
      }
    },
    // 切换tab
    handleClick(tab, event) { },
    getSubmit() { },
    getFromSelect(val, index, indexRow, obj) { },
    // 选择框点击事件
    async elDialogClick(row, index, indexRow) {
      this.organizationForm = {
        code: "",
        parentOrganName: "",
      };
      this.propLabel = row.prop;
      if (row.label == "所属业务员") {
      }

      if (row.label == "部门") {
        this.organization = "所属部门";
        this.$refs.baseOrganization.dialogVisible = true;
      }
      if (row.label == "对外签订单位") {
        this.organization = "对外签订单位";
        this.$refs.baseOrganization.dialogVisible = true;
      }
      if (row.label == "所属项目") {
        this.choiceTitle = "选择项目";
        this.tableColumn = configData.connection;
        this.choiceDialog = true;
      }
      if (row.label == "客户名称") {
        this.choiceTitle = "选择客商";
        this.supplierTableColumn = configData.companyTableColumn;
        this.connectionTree();
        this.supplierUnit = true;
      }
      if (row.label == "供方单位") {
        this.choiceTitle = "供方单位";
        this.supplierTableColumn = configData.supplierTableColumn;
        this.connectionTree();
        this.supplierUnit = true;
      }
      if (row.label == "业务员") {
        this.choiceTitle = "所属业务员";
        this.supplierTableColumn = configData.salesman;
        // this.OrganGetUser();
        // this.supplierUnit = true;
        this.$refs.baseRadioPeople.openDialog();
      }
    },
    // 获取人员列表
    async OrganGetUser() {
      this.connectionLoading = true;
      const res = await OrganGetUser({
        ...this.pageModel,
      });
      if (res.success == "true") {
        this.$refs.supplier.setPageTotal(res.data[0]);
        this.supplierTableData = res.data[1];
        this.connectionLoading = false;
      }
    },
    // 获取客户分类树
    async connectionTree() {
      this.connectionLoading = true;
      const res = await connectionTree({});
      if (res.success == "true") {
        this.itemTree1 = res.data[0];
      }
      this.connectionLoading = false;
    },
    // 获取客户列表
    async OrganGetCustomer() {
      this.connectionLoading = true;
      const res = await OrganGetCustomer({
        ...this.pageModel,
      });
      if (res.success == "true") {
        this.$refs.supplier.setPageTotal(res.data[0]);
        this.supplierTableData = res.data[1];
      }
      this.connectionLoading = false;
    },
    // 获取供货商列表
    async OrganGetSupplier() {
      this.connectionLoading = true;
      const res = await OrganGetSupplier({
        ...this.pageModel,
      });
      if (res.success == "true") {
        this.$refs.supplier.setPageTotal(res.data[0]);
        this.supplierTableData = res.data[1];
      }
      this.connectionLoading = false;
    },
    // 获取项目列表
    async projectDetails(id) {
      this.itemLoading = true;
      this.itemId = id;
      const res = await projectDetails({
        id, //项目分类ID
        ...this.pageModel,
      });
      if (res.success == "true") {
        this.choiceTableData = res.data[1];
        this.choiceTableData.forEach((el) => {
          el.endDate = this.formatTime(el.endDate);
          el.createDate = this.formatTime(el.createDate);
          el.beginDate = this.formatTime(el.beginDate);
        });
        this.$refs.choice.setPageTotal(res.data[0]);
      }
      this.itemLoading = false;
    },
    formatTime(row) {
      return row && row.substring(0, 10);
    },
    // 供方单位、客户名称弹窗分页变化
    supplierPage(model) {
      this.pageModel.page = model.page;
      this.pageModel.limit = model.limit;
      if (this.choiceTitle == "供方单位") {
        this.OrganGetSupplier();
      } else if (this.choiceTitle == "选择客商") {
        this.OrganGetCustomer();
      } else if (this.choiceTitle == "选择项目") {
        this.projectDetails(this.itemId);
      }
    },
    personConfirmClick(el) {
      this.$refs.customForm.getField("salesman", el.p_PersonID);
      this.$refs.customForm.getField("p_PersonName", el.p_PersonName);
    },
    // 选择供应商、客户
    choiceSupplier() {
      if (!this.$refs.supplier.optionData) {
        this.$vmNews("请选择一条");
        return;
      }
      //   this.$refs.customForm.choiceAssignment(this.$refs.supplier.optionData);
      if (this.choiceTitle == "供方单位") {
        // this.$refs.moneyCustomForm.getField(
        //   "venName",
        //   this.$refs.supplier.optionData.venName
        // );
        // this.$refs.moneyCustomForm.getField(
        //   "vendorCode",
        //   this.$refs.supplier.optionData.venCode
        // );
      } else if (this.choiceTitle == "选择客商") {
        this.$refs.customForm.getField(
          "cusName",
          this.$refs.supplier.optionData.cusName
        );
        this.$refs.customForm.getField(
          "customerCode",
          this.$refs.supplier.optionData.cusCode
        );
        this.$refs.customForm.getField(
          "customerPhone",
          this.$refs.supplier.optionData.telphone
        );
        this.$refs.customForm.getField(
          "customerContact",
          this.$refs.supplier.optionData.legalPerson
        );
      } else if (this.choiceTitle == "所属业务员") {
        this.$refs.customForm.getField(
          "salesman",
          this.$refs.supplier.optionData.p_PersonID
        );
        this.$refs.customForm.getField(
          "p_PersonName",
          this.$refs.supplier.optionData.p_PersonName
        );
      }
      this.$refs.supplier.$refs.customtable.clearRadioIndex();
      this.supplierUnit = false;
    },
    // 树状图点击事件
    handleNodeClick(data) {
      this.organizationForm = {
        code: data.code,
        parentOrganName: data.label,
      };
      this.propvalue = data.label;
    },
    organizationHandleConfirm(val) {
      if (this.organization == "所属部门") {
        // this.$refs.customForm.getField("organID", val.label);
        this.$refs.customForm.getField("organID", val.id);
        this.$refs.customForm.getField("organName", val.label);
      } else if (this.organization == "对外签订单位") {
        this.$refs.customForm.getField("companyName", val.label);
        this.$refs.customForm.getField("companyNameID", val.id);
      }
      this.$refs.baseOrganization.qingkong();
      this.$refs.baseOrganization.dialogVisible = false;
    },
    choiceHandleConfirm() {
      if (!this.$refs.choice.optionData) {
        this.$vmNews("请选择一条");
        return;
      }
      this.$refs.customForm.getField(
        "projectCode",
        this.$refs.choice.optionData.billCode
      );
      this.$refs.customForm.getField(
        "projectName",
        this.$refs.choice.optionData.projectName
      );
      this.choiceDialog = false;
    },
    getTableList(data) {
      console.log("查询");
    },
  },
};
</script>
<style scoped lang="scss">
.box {
  background-color: white;
  margin: 40px 10px 10px 10px;
  border-radius: 5px;

  .title {
    font-size: 16px;
    color: #000;
    border-left: 3px solid #2261f6;
    padding-left: 8px;
    text-align: left;
  }
}

.title_box {
  width: 100%;
  border-bottom: 1px solid #fafafa;
  padding-bottom: 10px;

  .operate {
    color: #409eff;
  }
}

::v-deep .el-collapse-item {
  border-bottom: 10px solid #fafafa;
  padding: 0 10px;
}

::v-deep .el-collapse-item__header {
  height: auto;
  line-height: normal;
  padding: 15px 0;
  border-bottom: none;
}

::v-deep .el-collapse-item__arrow {
  margin-bottom: 8px;
  color: #409eff;
}

::v-deep .el-dialog__body {
  padding: 0 !important;
}

.el-dialog__wrapper {
  ::v-deep .el-dialog__headerbtn {
    display: none;
  }

  ::v-deep .el-dialog__header {
    text-align: center;
  }

  ::v-deep .el-dialog__body {
    height: 300px;
  }

  ::v-deep .el-button--medium {
    margin: 100px 0;
  }
}

::v-deep .el-collapse-item__content {
  padding-bottom: 0;
  position: relative;
}

::v-deep .el-form-item__content {
  div {
    p {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

::v-deep .el-row {
  height: 42px;
}

::v-deep .el-collapse-item__wrap {
  border-bottom: none;
}

::v-deep .el-row {
  height: 47px !important;
}

::v-deep .el-form-item__content {
  height: 34px;
}
</style>