<template>
  <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="save('true')">提交审核</el-button>
    </div>
    <div v-loading="loading">
      <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"
            :spanNumber="spanNumber" style="padding: 10px 0" justifyContent="flex-end"
            :rules="rules" @elDialogClick="elDialogClick">
          </base-form>
        </el-collapse-item>
      </el-collapse>
    </div>
    <base-radio-people ref="baseRadioPeople" @personConfirmClick="personConfirmClick"></base-radio-people>
    <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="客户名称" width="90%" top="10vh"
      :footerShow="true">
      <div style="display: flex; margin: 10px 0 0 10px">
        <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"
           @handleNodeClick="classifyTree" ref="supplier" :choiceDialog="choiceDialog"
          v-loading="connectionLoading" :menuData="itemTree1"></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 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 { dataDictionaryGetBillList } from "@/api/apis/dataDictionary";
import { submitAudit } from "@/api/apis/audit";
import { GetOrganTree,connectionTree,OrganGetCustomer } from "@/api/apis/organization";
import { SaveData,GetBillData } from '@/api/apis/opportunityManagement'
export default {
  name: "NewOpportunities",
  components: {
    baseForm,
    baseTree,
    baseDialog,
    baseLayout,
    baseChoice,
    baseOrganization,
    baseRadioPeople,
  },
  data() {
    return {
      sourceData: [],
      stateData: [],
      activeName: "first",
      topFormRow: configData.topFormRow,
      isFunBtn: false,
      spanNumber: 6,
      organization: "",
      activeNames: ["1"],
      flex: "flex-end",
      arr1: "",
      arr2: "-1",
      stageList: [],
      rules: configData.formVerification,
      firstOpen: true,
      refresh: true,
      tableData: [],
      loading: false,
      billid: '',
      organMenuData: [],
      supplierTableColumn: configData.companyTableColumn,
      supplierUnit: false,
      queryCriteria: '',
      itemTree1: [],
      supplierTableData: [],
      pageModel: {
        page: 1, //当前页码
        limit: 10, //每页显示多少
        cusClassify: "", //树形分类id
        Sequence: "", //排列方式
        SequenceName: "", //需要排列的字段名
        CodeOrName: "",
      },
      connectionLoading: false,
      choiceDialog: false
    };
  },
  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再进行修改
      } else {
        vm.$set(to.meta, "title", '新增商机');
      }
    }); //切记操作完一定要记得放行,否则无法正常跳转页面
  },
  created() {
    this.initialization()
  },
  methods: {
    initialization() {
      this.loading = true
      this.selectData()
      this.getMenuData()
      if (this.$route.query.name == '编辑商机') {
        this.billid = this.$route.query.id
        this.GetBillData()
      }
      this.refresh = false;
      this.$route.query.Refresh = false;
    },
    // 获取详情
    async GetBillData() {
      const res = await GetBillData({
        id: this.billid,
        op: ''
      })
      if (res.success == 'true') {
        this.$refs.customForm.choiceAssignment(res.data[0])
        this.$refs.customForm.getField("contractCode", res.data[0].billCode);
      }
      this.loading = false
    },
    async getMenuData() {
      let params = {
        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 selectData() {
			let params = {
        		page: 1,
        		limit: 999,
        		Sequence: "",
        		SequenceName: "",
			}
			const res = await dataDictionaryGetBillList({...params,KindId: 59})
      		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.sourceData = arrList
      		  }
      		  configData.topFormRow[2].elCol[0].options = arrList;
      		}
			const item = await dataDictionaryGetBillList({...params,KindId: 63})
      if (item.code == 1) {
        let list = [];
        if (item.data[0] > 0) {
          item.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            list.push(arr);
          });
          this.stateData = list
        }
        configData.topFormRow[2].elCol[1].options = list;
      }
			const e = await dataDictionaryGetBillList({...params,KindId: 64,})
      if (e.code == 1) {
        let list = [];
        if (e.data[0] > 0) {
          e.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            list.push(arr);
          });
          this.stateData = list
        }
        configData.topFormRow[3].elCol[1].options = list;
      }
			const a = await dataDictionaryGetBillList({...params,KindId: 65,})
      if (a.code == 1) {
        let list = [];
        if (a.data[0] > 0) {
          a.data[1].forEach((el) => {
            let arr = {
              label: el.ddd_DicDetailsName,
              value: el.ddd_DicDetailsID,
            };
            list.push(arr);
          });
          this.stateData = list
        }
        configData.topFormRow[4].elCol[0].options = list;
      }
      this.loading = false
		},
    // 新增一行
    stageAdd() {
      this.$refs.contractStage.add();
    },
    // 表单点击
    elDialogClick(row, index, indexRow) {
      if (row.label == "业务人员") {
        this.$refs.baseRadioPeople.openDialog();
      }
      if (row.label == "销售部门") {
        this.$refs.baseOrganization.dialogVisible = true;
      }
      if (row.label == "客户名称") {
        this.connectionTree();
        this.supplierUnit = true;
      }
    },
    // 获取客户分类树
    async connectionTree() {
      this.connectionLoading = true;
      const res = await connectionTree({});
      if (res.success == "true") {
        this.itemTree1 = res.data[0];
      }
      this.connectionLoading = false;
    },
    // 业务人员
    personConfirmClick(el) {
      this.$refs.customForm.getField("personID", el.p_PersonID);
      this.$refs.customForm.getField("personName", el.p_PersonName);
    },
    // 销售部门
    organizationHandleConfirm(el) {
      this.$refs.customForm.getField("organID", el.id);
      this.$refs.customForm.getField("organName", el.label);
      this.$refs.baseOrganization.dialogVisible = false;
    },
    // 查询
    queryClick() {
        this.pageModel.CodeOrName = this.queryCriteria;
        this.OrganGetCustomer();
    },
    // 关闭客户名称弹窗
    close() {
      this.queryCriteria = "";
      this.itemTree1 = [];
      // this.supplierTableData = [];
      this.$refs.supplier.setPageTotal(0);
    },
    // 分类树点击
    classifyTree(item) {
        this.pageModel.cusClassify = item.id;
        this.pageModel.codeOrName = this.queryCriteria;
        this.OrganGetCustomer();
    },
    //  分页变化
    supplierPage(model) {
      this.pageModel.page = model.page;
      this.pageModel.limit = model.limit;
      this.OrganGetSupplier();
    },
    // 获取客户列表
    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;
    },
    // 客户名称
    choiceSupplier() {
      if (!this.$refs.supplier.optionData) {
        this.$vmNews("请选择一条");
        return;
      }
      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;
    },
    // 保存
    async save(item) {
      this.$refs.customForm.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.submitTo(item);
        } else {
          this.$message({
            message: "请输入必填项",
            type: "warning",
          });
          return;
        }
      });
    },
    handleChange(val, index) {
      this.arr1 = val.indexOf("1");
    },
    async submitTo(item) {
      let data = {
        dataMain: {
          billid: '00000000-0000-0000-0000-000000000000',
          ...this.$refs.customForm.ruleForm,
        },
      }
      const res = await SaveData(data)
      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: "171", //单据类型ID
        });
        if (obj.success == "true") {
          this.$message({
            message: "提交审核成功",
            type: "success",
          });
          this.$router.push({
            path: "viewOpportunity",
            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: "viewOpportunity",
            query: {
              id: this.billID,
              Refresh: true,
            },
          });
          this.$store.dispatch("tagsView/delView", this.$route);
      }
    },
  }
};
</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-row:nth-child(2) {
  height: 65px !important
}

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