<template>
  <div class="main" style="height: auto">
    <div class="headerRadio">
      <el-radio-group size="small" v-model="approvalType" border class="custom-radio" v-for="(item) in businessAndTemList" :key="item.id">
        <el-radio-button :label="item.id">{{ item.business_name }}</el-radio-button>
      </el-radio-group>
    </div>
    <!-- <div class="selectForm">
      <el-form ref="form" :inline="true" :model="form" class="demo-form-inline" :rules="rules">
        <el-form-item label="发起人手机号:" prop="phone">
          <el-input size="small" v-model="form.phone" placeholder="请输入发起人手机号"></el-input>
        </el-form-item>
        <el-form-item label="选择审批单:" prop="code">
          <el-select v-model="form.code" placeholder="请选择审批单" @change="changeSelect" ref="select">
            <el-option :label="item.process_name" :value="item.process_code" v-for="item in selectList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div> -->
    <!--    审批单界面-->
    <div class="mainApproval" style="background-color: white">
      <div v-for="(child, index) in childComponents" :key="index" style="padding-top: 20px">
        <commonGrid  :approvalType="approvalType" :index="index" :childComponents="childComponents" ref="kk" v-if="flag" :childFlag="childFlag" @updateChildComponents="updateChildComponents">
        </commonGrid>
        <el-divider></el-divider>
      </div>
      <div class="footerBtn">
        <el-button size="small" type="primary" @click="addApprovalNode" v-show="this.childComponents.length <= 2">添加审核节点 </el-button>
        <el-button size="small" type="danger" @click="deleteApprovalNode" :disabled="childComponents.length <= 1">删除审核节点 </el-button>
        <el-button size="small" type="success" v-debounce="submitAll">提交全部审核</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import gridOne from "@/views/operation/approval/approvalConfig/approvalGrid/gridOne.vue";
import gridTwo from "@/views/operation/approval/approvalConfig/approvalGrid/gridTwo.vue";
import gridThree from "@/views/operation/approval/approvalConfig/approvalGrid/gridThree.vue";
import commonGrid from "@/views/operation/approval/approvalConfig/approvalGrid/commonGrid.vue";
import { mapState } from "vuex";
import { reqAllPeopleInfo, reqGetBusinessList, reqSaveAllPeople, getApvFormAPI, sendKeyCresteAPI, getIdByPhoneAPI } from "@/api/finance/approval";
import debounce from "@/utils/directives/debounce"
export default {
  name: "approvalConfig",
  components: { gridOne, gridTwo, gridThree, commonGrid },
  directives: {
    debounce,
  },
  data() {
    return {
      approvalType: null,
      flag: false,
      childComponents: [],
      addAndDeleteBtn: false,
      childFlag: true,
      orgid: sessionStorage.getItem('orgid'),
      user_id: sessionStorage.getItem('userId'),
      form: {
        phone: '',
        code: ''
      },
      rules: {
        phone: [{ pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: "请输入有效的手机号" },
        { required: true, trigger: "blur", message: "请输入手机号" }],
        code: [
          { required: true, message: '请选择审批单', trigger: 'change' }
        ],
      },
      selectList: [],
      selectLabel: '',
      phoneId: ""
    };
  },
  created() {
    if (this.businessAndTemList.length > 0) {
      this.approvalType = this.businessAndTemList[0].id
    }
  },
  async mounted() {
    await this.initHeaderRadio()
    this.flag = true
    this.getApvForm()
  },
  computed: {
    ...mapState({
      approvalAllPeople: state => state.approval.approvalAllPeople,
      approvalAllPeopleShowState: state => state.approval.approvalAllPeopleShowState,
      allPeopleInfo: state => state.approval.allPeopleInfo,
      isFullFormChild: state => state.approval.isFullFormChild,
      businessAndTemList: state => state.approval.businessAndTemList
    })
  },
  methods: {
    getApvForm() {//获取审批模板
      getApvFormAPI().then(res => {
        if (res.status == true) {
          this.selectList = res.data
        }
      })
    },
    getIdByPhone(params) {//获取回显手机号
      getIdByPhoneAPI(params).then(res => {
        if (res.status == true) {
          if (res.data) {
            // res.data   ?? 这不是数组么, 打点什么意思.怎么写?什么玩意 有的是数组 有的是对象, 给我骂后端....
            this.form.phone = res.data.send_dd_user_phone
            this.form.code = res.data.process_code
            this.phoneId = res.data.id ? res.data.id : ''
            this.selectLabel = res.data.process_name
          }
        } else {
          this.$refs.form.resetFields();
        }
      })
    },
    changeRadio(index) {
      this.getIdByPhone({ orgid: this.orgid, business_id: index })
    },
    changeSelect(code) {
      this.selectLabel = this.selectList.find(item => { return item.process_code == code }).process_name;
    },
    initHeaderRadio() { //获取全部上方Radio列表
      reqGetBusinessList().then(res => {//获取全部列表信息
        if (res.status) {
          this.$store.commit('GETBusinessAndTemList', res.data)
          if (res.data.length > 0) {
            this.approvalType = this.businessAndTemList[0].id //radio设为第一个高亮
            // this.getIdByPhone({ orgid: this.orgid, business_id: this.approvalType })
            reqAllPeopleInfo({
              "orgid": this.orgid,
              "business_id": this.approvalType
            }).then(res => {
              if (JSON.stringify(res.data) !== "{}") {
                this.$store.commit('GETALLPEOPLEINFO', res.data)
                this.childComponents = Object.keys(this.allPeopleInfo.levels)
              } else {
                this.childFlag = false
                this.childComponents = [0]
              }
            })
            if (JSON.stringify(this.levels) == {}) {
              this.childComponents = [0]
            } else {
              this.addAndDeleteBtn = true
            }
          } else {//radio为空
            this.open()
          }
        }
      })
    },

    open() { //弹窗提醒
      this.$alert('当前业务为空，请先添加业务信息！', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          this.$router.push({
            name: 'approvalBusinessConfig',
            path: '/operation/approval/approvalArgumentsConfig',

          })
          // this.$message({
          //   type: 'info',
          //   message: `action: ${action}`
          // });
        }
      });
    },
    submitAll() {
      if (!this.isFullFormChild) {
        this.$store.commit('changeFormIsFull', true)
      }
      this.$store.commit('setApprovalAllPeopleFull')
      for (let i = 0; i < this.childComponents.length; i++) {
        this.$refs.kk[i].submitData()
      }
      if (!this.isFullFormChild) {
      } else {
        let lastResult = {}
        lastResult['user_id'] = this.user_id
        lastResult['orgid'] = this.orgid
        lastResult['business_id'] = this.approvalType
        lastResult['flag'] = JSON.stringify(this.approvalAllPeople) =={} ? "add" : "update"
        lastResult["level_data"] = this.approvalAllPeople
        reqSaveAllPeople(lastResult).then(res => {
          if (res.status) {
            this.$message.success('保存成功!')
          } else {
            this.$message.error(res.msg)
          }
        })
        reqAllPeopleInfo({
          "orgid": this.orgid,
          "business_id": this.approvalType
        })
      }

    },
    addApprovalNode() {
      this.childComponents.push(this.childComponents[this.childComponents.length - 1] + 1)
      this.childFlag = false
    },
    deleteApprovalNode() {
      this.childComponents.pop()
    },
    updateChildComponents(newValue) {
      this.childComponents = newValue;
    },
  },
  // watch: {
  //     approvalType: {
  //         handler(newValue) {
  //             console.log('watch执行了')
  //             reqAllPeopleInfo({
  //                 "orgid": this.orgid,
  //                 "business_id": newValue
  //             }).then(res => {
  //                 // this.childComponents = Object.keys(this.allPeopleInfo.levels)
  //                 // this.$store.commit('GETALLPEOPLEINFO',res.data)
  //                 // this.$store.commit('setApprovalAllPeopleFull')
  //                 //
  //                 //
  //                 // let levels =res.data.levels
  //                 // let keys = Object.keys(levels)
  //                 // for (let i = 0; i < keys.length; i++) {
  //                 //   let temp=keys[i]
  //                 //   let item ={
  //                 //    "apv_dd_user_id":levels[keys[i]]
  //                 //   }
  //                 //   // this.$store.commit('SETAPPROVALaLLPEOPLE',item)
  //                 // }
  //                 //
  //                 // for (let i = 0; i < this.childComponents.length; i++) {
  //                 //   this.$refs.kk[i].initData()
  //                 // }
  //                 // console.log(res.data)
  //             })

  //         }
  //     }
  // }
}
</script>

<style scoped lang="scss">
.mainApproval {
  width: 80%;
  //height: calc(100vh - 10px);

  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  background-color: white;
  margin: 20px auto;
}

.headerRadio {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-bottom: 15px;
}

.selectForm {
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-radio {
  position: relative;
}

.custom-radio::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 16px;
  height: 16px;
  border: 1px solid #ccc;
  /* 设置边框样式和颜色 */
  border-radius: 50%;
  /* 使边框变为圆形 */
  box-sizing: border-box;
}

.custom-radio .el-radio__inner {
  position: relative;
  z-index: 1;
}

.footerBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding-bottom: 20px;
}
</style>
