<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">
          </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">相关联系人({{ stageList.length }})</span>
              <span class="operate">{{ arr2 == -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>
    </div>
  </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 contractStage from "./contractStage.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 { SaveData,GetBillData } from '@/api/apis/leadManagement'
import { dataDictionaryGetBillList } from "@/api/apis/dataDictionary";
import {  submitAudit } from "@/api/apis/audit";
export default {
  name: "NewLead",
  components: {
    baseForm,
    baseTree,
    baseDialog,
    baseLayout,
    baseChoice,
    contractStage,
    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: ''
    };
  },
  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()
  },
  mounted() {
    this.stageList = this.$refs.contractStage.tableData
  },
  methods: {
    initialization() {
      this.loading = true
      this.selectData()
      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.contractStage.tableData = res.data[1]
        this.stageList = res.data[1]
        this.$refs.customForm.getField("contractCode", res.data[0].billCode);
      }
      this.loading = false
    },
		// 数据字典
		async selectData() {
			let params = {
				KindId: 55,
        		page: 1,
        		limit: 999,
        		Sequence: "",
        		SequenceName: "",
			}
			const 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.sourceData = arrList
      		  }
      		  configData.topFormRow[0].elCol[1].options = arrList;
      		}

			let data = {
				KindId: 56,
        		page: 1,
        		limit: 999,
        		Sequence: "",
        		SequenceName: "",
			}
			const item = await dataDictionaryGetBillList(data)
      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[0].elCol[2].options = list;
      }
      this.loading = false
		},
    // 新增一行
    stageAdd() {
      this.$refs.contractStage.add();
    },
    // 保存
    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");
      this.arr2 = val.indexOf("2");
    },
    async submitTo(item) {
      let contacts = JSON.parse(
        JSON.stringify(this.$refs.contractStage.tableData)
      );
      for (let i = 0; i < contacts.length; i++) {
        if (!contacts[i].personName || contacts[i].personName == "") {
          this.$message({
            message: `请录入相关联系人行${i + 1}姓名`,
            type: "warning",
          });
          return;
        } else if (!contacts[i].phone || contacts[i].phone == "") {
          this.$message({
            message: `请录入相关联系人行${i + 1}联系方式`,
            type: "warning",
          });
          return;
        }
      }
      let data = {
        dataMain: {
          billid: '00000000-0000-0000-0000-000000000000',
          ...this.$refs.customForm.ruleForm,
        },
        dataContacts: []
      }
      this.$refs.contractStage.tableData.forEach(el => {
        data.dataContacts.push({
          mainID: '00000000-0000-0000-0000-000000000000',
          ...el,
          rowIndex: el.index,
        })
      })
      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: "170", //单据类型ID
        });
        if (obj.success == "true") {
          this.$message({
            message: "提交审核成功",
            type: "success",
          });
          this.$router.push({
            path: "viewClue",
            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: "viewClue",
            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(3) {
  height: 65px !important
}

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