<template>
  <!-- S 新增 编辑弹窗 -->
  <div style="
      background-color: #fafafa;
      height: calc(100vh - 80px);
      overflow-y: auto;
    ">
    <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="handleClick('true')">确定</el-button>
    </div>
    <div v-loading="itemLoading">
      <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>
          <el-button type="primary" plain @click="agreementAdd" v-if="agreementList.length == '0'" icon="el-icon-plus"
            circle style="
              position: absolute;
              top: 54px;
              left: 14px;
              z-index: 999;
              padding: 6px;
            ">
          </el-button>
          <project-team ref="projectTeam" @callBackInfo="handlInfo"></project-team>
        </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>
          <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" :infos="infos" @callBackInfo="handlStage"></contract-stage>
        </el-collapse-item>

        <el-collapse-item name="4">
          <template slot="title">
            <div class="title_box" flex="cross:center main:justify">
              <span class="title">附件管理</span>
              <span class="operate">{{ arr4 == -1 ? "展开" : "收起" }}</span>
            </div>
          </template>
          <attachment-management ref="attachment"></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="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-dialog :closeEscape="true" :showClose="true" :closeModal="false" @handleConfirmClick="choiceContractCode"
      :dialogVisible.sync="contractCodeDialog" :title="choiceTitle" width="90%" top="10vh" :footerShow="true">
      <div class="connection">
        <base-choice @onQuery="contractPage" :tableColumn="contractCodeTableColumn" :tableData="contractCodeTableData"
          @getTableList="getTableList" ref="contractCode" :choiceDialog="choiceDialog" v-loading="contractCodeLoading">
        </base-choice>
      </div>
    </base-dialog>
  </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 projectTeam from "./projectTeam.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 { getInfo } from "@/utils/auth.js";
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 { personListByRole } from "@/api/apis/personnelSettings";
import {
  projectList,
  projectDetailData,
  projectSaveData,
  projectDelData,
  projectProMemberDelData,
  projectProPhaseDelData,
} from "@/api/apis/projectManagement";
import { getContractList, OrganDelContract, typeOfContract, } from "@/api/apis/contract";
import { BillMachineGetBillQueryPlan, GetDataSourcePerson, BillMachineGetDataSource, BillMachineSaveDataSource } from "@/api/apis/documentManagement";
import {
  getAuditBtn,
  getAuditNote,
  audit,
  submitAudit,
} from "@/api/apis/audit";
export default {
  name: "AddEditChange",
  components: {
    baseForm,
    baseTree,
    baseDialog,
    baseLayout,
    baseChoice,
    projectTeam,
    contractStage,
    attachmentManagement,
    baseOrganization,
    baseRadioPeople,
  },
  data() {
    return {
      projectFileDialog: false,
      dialogType: "新增", //表格类型

      tableColumn: {},
      isFunBtn: false,
      spanNumber: 6,
      choiceTitle: "",
      topFormRow: configData.topFormRow,//基本信息form字段
      rules: configData.formVerification,//基本信息校验
      choiceDialog: false, //选择组织机构弹窗

      supplierTableColumn: [], // 供方表头
      supplierTableData: [], // 供方表体
      supplierUnit: false, // 供方单位弹窗
      contractCodeDialog: false,//合同号弹窗
      contractCodeTableColumn: [],//合同号弹窗--表头
      contractCodeTableData: [],//合同号弹窗--表体
      contractCodeLoading: false,//
      organMenuData: [],//部门弹窗--树
      organizationForm: {},
      propLabel: "",
      pageModel: {
        page: 1, //当前页码
        limit: 20, //每页显示多少
        cusClassify: "", //树形分类id
        Sequence: "", //排列方式
        SequenceName: "", //需要排列的字段名
        CodeOrName: "",
      },
      organization: "",
      dropList1: [],
      dropList2: [],
      dropList3: [],
      dropList4: [],
      dropList5: [],
      itemTree1: [],
      itemLoading: false,
      connectionLoading: false,
      flex: "flex-end",
      dialogVisible: false,
      infos: [],//项目组成员数据
      agreementList: [],
      stageList: [],
      //
      activeName: "first",
      activeNames: ["1"],
      arr1: "",
      arr2: "-1",
      arr3: "-1",
      arr4: "-1",
      //
      typeLoading: false,
      queryCriteria: "",
      billID: "",
      switch: false,
      notSelected: false,
      clickSave: false,
      addEditChange: null,
      queryId: null,
      fullscreenLoading: false,
      firstOpen: true,
      refresh: true,
      CreatePersonID: "",
      affiliatedPersons: [],
    };
  },
  watch: {
    // 新增编辑弹窗
    projectFileDialog: {
      deep: true,
      handler(newValue, oldValue) {
        if (newValue === false) {
          // 重置表单
          this.$refs.attachment.tableData = [];
          this.$refs.projectTeam.tableData = [];
          this.$refs.contractStage.tableData = [];
          this.$refs.customForm.resetFields("ruleForm");
        }
      },
    },
  },
  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;
  },

  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再进行修改
      }
    }); //切记操作完一定要记得放行,否则无法正常跳转页面
  },
  created() {
    this.inPage();
  },

  mounted() {
    // this.agreementList = this.$refs.projectTeam.tableData;
    // this.stageList = this.$refs.contractStage.tableData;
  },

  methods: {
    handlInfo(data) {
      this.infos = data
      this.agreementList = data
    },
    handlStage(val) {
      this.stageList = val
    },
    // 页面初始化
    inPage() {
      this.addEditChange = this.$route.query.name;
      if (this.addEditChange && (this.addEditChange == "项目编辑" || this.addEditChange == "项目查看")) {
        this.init();
      }
      this.getMenuData();
      this.getSalesCodeList(); //业务员
      this.getProductIDList(); //产品线
      this.getProStateList(); //项目状态
      this.getProManList(); //项目经理
      this.getProClassifyNameList(); //项目类型
      this.OrganGetProject();

      this.refresh = false;
      this.$route.query.Refresh = false;
    },
    init() {
      this.queryId = this.$route.query.id;
      this.getrowDetails();
    },
    initialization(val) {
      // console.log(this.detailedList, "this.detailedList");
      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.getField("createDate", time);
    },
    stageAdd() {
      this.$refs.contractStage.add();
    },
    agreementAdd() {
      this.$refs.projectTeam.add(1);
    },
    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");
    },
    //保存
    handleClick() {
      this.$refs.customForm.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let params = {
            saveType: "",
            op: "",
            dataMain: {
              billid:
                this.dialogType == "新增"
                  ? "00000000-0000-0000-0000-000000000000"
                  : this.queryId,
              billCode: "",
              ...this.$refs.customForm.ruleForm,
            },
            business_ProMember: [],
            business_ProPhase: [],
            attIDS: this.$refs.attachment.appendix.join(),
          };
          this.$refs.contractStage.tableData.forEach((el) => {
            params.business_ProPhase.push({
              // mainID: "00000000-0000-0000-0000-000000000000",
              ...el,
              affiliatedPersons: el.affiliatedPersons.length > 0 ? el.affiliatedPersons.join(",") : '',
              rowIndex: el.index,
            });
          });
          this.$refs.projectTeam.tableData.forEach((el) => {
            params.business_ProMember.push({
              // mainID: "00000000-0000-0000-0000-000000000000",
              ...el,
              rowIndex: el.index,
            });
          });
          this.save(params);
        } else {
          this.$message({
            message: "请输入必填项",
            type: "warning",
          });
          return;
        }
      });
    },
    async save(params) {
      let res = await projectSaveData(params);
      if (res.code == 1) {
        this.$vmNews("保存成功", "success");
        this.billID = res.data[0];
        this.getrowDetails()
      }
      this.$router.push({
        path: "projectSee",
        query: {
          id: this.billID,
          Refresh: true,
        },
      });
      this.$store.dispatch("tagsView/delView", this.$route);
    },
    // 当前详情数据
    async getrowDetails() {
      this.itemLoading = true;
      let params = {
        id: this.queryId,
        op: "",
      };
      let res = await projectDetailData(params);
      if (res.code === 1) {
        let data = res.data;
        // 编辑
        if ((this.addEditChange = "项目编辑")) {
          this.$refs.customForm.choiceAssignment(data[0]);
          this.$refs.projectTeam.tableData = data[1];
          this.$refs.contractStage.tableData = data[2];
          this.$refs.contractStage.tableData.forEach((el, index) => {
            el.affiliatedPersons = data[2][index].affiliatedPersons.split(',')
          })

          this.$refs.attachment.UploadList1(data[3]);
          this.itemLoading = false;
        }
      }
    },
    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.supplierTableData = [];
      this.$refs.supplier.setPageTotal(0);
    },

    //合同号弹窗--列表
    async getContractList() {
      this.contractCodeLoading = true;
      const res = await getContractList({
        page: 1, limit: 999, sequence: "", SequenceName: "", CodeOrName: "", ConType: "",
      });
      if (res.code == 1) {
        this.$refs.contractCode.setPageTotal(res.data[0]);
        this.contractCodeTableData = res.data[1];

      }
      const el = await GetDataSourcePerson({ billKindID: '45' })
      if (el.code == 1) {
        this.contractCodeTableColumn = el.data[1].length == 0 ? el.data[0] : el.data[1]
        this.contractCodeTableColumn.forEach(el => {
          el.tooltip = true
        });
        this.contractCodeLoading = false;
      }
      this.$refs.contractCode.clearRadioIndex()
    },
    // 选择合同号弹窗--分页变化
    contractPage(model) {
      this.pageModel.page = model.page;
      this.pageModel.limit = model.limit;
      if (this.choiceTitle == "合同号") {
        this.getContractList();
      }
    },
    // 选择合同号弹窗--选择数据
    choiceContractCode() {
      if (!this.$refs.contractCode.optionData) {
        this.$vmNews("请选择一条数据");
        return;
      }
      if (this.choiceTitle == "合同号") {
        this.$refs.customForm.getField("projectName", this.$refs.contractCode.optionData.conName);
        this.$refs.customForm.getField("contractCode", this.$refs.contractCode.optionData.contractCode);
      }
      this.$refs.contractCode.$refs.customtable.clearRadioIndex();
      this.contractCodeDialog = false;
    },


    // 获得组织树状图
    async getMenuData() {
      let params = {
        // CompanyID: 1
        companyID: this.$store.state.user.companyID
          ? this.$store.state.user.companyID
          : getCompanyId(),
      };
      let res = await GetOrganTree(params);
      console.log(res);
      this.organMenuData = JSON.parse(res.data[0]);
    },
    // 获取项目分类
    async OrganGetProject() {
      let res = await ProjectClassification({});
      if (res.code == 1) {
        this.itemTree = res.data[0];
      }
    },
    // 获取业务员类型
    async getProManList() {
      let res = await personListByRole({
        roleID: "b83261c2-72ea-4857-863f-a5eb6dae6856",
      });
      if (res.code == 1) {
        let arrList = [];
        if (res.data.length > 0) {
          res.data[0].forEach((el) => {
            let arr = {
              label: el.personName,
              value: el.personID,
            };
            arrList.push(arr);
          });
        }
        this.dropList2 = arrList;
        configData.topFormRow[0].elCol[3].options = arrList;
      }
    },
    //  获取产品线类型
    async getProductIDList() {
      let params = {
        KindId: 42,
        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[2].elCol[0].options = arrList;
      }
    },
    // 获取项目状态类型
    async getProStateList() {
      let params = {
        KindId: 51,
        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.dropList1 = arrList;
        configData.topFormRow[2].elCol[1].options = arrList;
      }
    },
    // 获取项目类型
    async getProClassifyNameList() {
      let params = {
        KindId: 54,
        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.dropList4 = arrList;
        configData.topFormRow[1].elCol[3].options = arrList;
      }
    },

    // 获取项目经理
    async getSalesCodeList() {
      let res = await personListByRole({
        roleID: "b872c6d6-32bc-4951-944e-99a92086c95f",
      });
      if (res.code == 1) {
        let arrList = [];
        if (res.data.length > 0) {
          res.data[0].forEach((el) => {
            let arr = {
              label: el.personName,
              value: el.personID,
            };
            arrList.push(arr);
          });
        }
        this.dropList5 = arrList;
        configData.topFormRow[1].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.projectTeam.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.attachment.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.projectTeam.tableData.filter((item) => {
        return item.detail_ID;
      });
      let list4 = this.$refs.projectTeam.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.projectTeam.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.projectTeam.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);
        }
      }
    },
    // 分类树点击
    classifyTree(item) {
      if (this.choiceTitle == "选择客商") {
        this.pageModel.cusClassify = item.id;
        this.pageModel.codeOrName = this.queryCriteria;
        this.OrganGetCustomer();
      }
    },
    getFromSelect(val, index, indexRow, obj) {
      console.log(obj);
    },

    // 选择框点击事件
    async elDialogClick(row, index, indexRow) {
      this.organizationForm = {
        code: "",
        parentOrganName: "",
      };
      this.propLabel = row.prop;
      if (row.label == "所属部门") {
        this.organization = "所属部门";
        this.$refs.baseOrganization.dialogVisible = true;
      }
      if (row.label == "客户名称") {
        this.choiceTitle = "选择客商";
        this.supplierTableColumn = configData.companyTableColumn;
        this.connectionTree();
        this.supplierUnit = true;
      }
      if (row.label == "合同号") {
        this.choiceTitle = "合同号";
        // this.contractCodeTableColumn = configData.contractCodeTableColumn;
        this.contractCodeDialog = true;
        this.getContractList();//合同号列表

      }

    },
    // 获取人员列表
    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;
      }
    },

    //日期
    formatTime(row) {
      return row && row.substring(0, 10);
    },
    // 获取客户弹窗--分类树
    async connectionTree() {
      this.connectionLoading = true;
      const res = await connectionTree({});
      if (res.success == "true") {
        this.itemTree1 = res.data[0];
      }
      this.connectionLoading = false;
    },
    // 选择客户弹窗--查询
    queryClick() {
      if (this.choiceTitle == "选择客商") {
        this.pageModel.CodeOrName = this.queryCriteria;
        this.OrganGetCustomer();
      }
    },
    // 获取客户弹窗--列表
    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;
    },
    // 选择客户弹窗--分页变化
    supplierPage(model) {
      this.pageModel.page = model.page;
      this.pageModel.limit = model.limit;
      if (this.choiceTitle == "选择客商") {
        this.OrganGetCustomer();
      }
    },
    // 选择客户弹窗--选择数据
    choiceSupplier() {
      if (!this.$refs.supplier.optionData) {
        this.$vmNews("请选择一条");
        return;
      }
      //   this.$refs.customForm.choiceAssignment(this.$refs.supplier.optionData);
      if (this.choiceTitle == "选择客商") {
        this.$refs.customForm.getField("cusName", this.$refs.supplier.optionData.cusName);
        this.$refs.customForm.getField("cusCode", this.$refs.supplier.optionData.cusCode);
      }
      this.$refs.supplier.$refs.customtable.clearRadioIndex();
      this.supplierUnit = false;
    },

    // 选择部门弹窗--树状图点击事件
    handleNodeClick(data) {
      console.log(data);
      this.organizationForm = {
        code: data.code,
        parentOrganName: data.label,
      };
      this.propvalue = data.label;
    },
    //选择部门弹窗--确定
    organizationHandleConfirm(val) {
      console.log(val);
      if (this.organization == "所属部门") {
        // this.$refs.customForm.getField("organID", val.label);
        this.$refs.customForm.getField("organID", val.id);
        this.$refs.customForm.getField("orgainName", val.label);
      }
      this.$refs.baseOrganization.qingkong();
      this.$refs.baseOrganization.dialogVisible = false;
    },

    getTableList(data) {
      console.log("查询");
    },
  },
};
</script>
<style scoped lang="scss">
.box {
  background-color: white;
  margin: 35px 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>
