<template>
  <el-dialog
    :visible.sync="isOpenDialog"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    top="5vh"
    title="添加指标"
    @close="cancelHandle"
    custom-class="dialog"
    center
    width="780px"
    v-dialogDrag
  >
    <div
    v-loading="isAddLoading"
    element-loading-text="加载时间大概五分钟，关闭弹窗不影响加载"
    element-loading-spinner="el-icon-loading">
      <div class="dialog-main">
        <el-row :gutter="10" class="row" style="margin-bottom: 15px;">
          <el-col style="width: 250px;" class="col title-col">指标ID</el-col>
          <el-col style="width: 382px;" class="col title-col">所属分类</el-col>
        </el-row>
        <el-form :model="edbForm" ref="edbFormDataListRef" >
          <div class="form-box" ref="formBoxRef">
            <el-row v-for="(item,index) in edbForm.edbDataList" :key="item.edbIndex" :gutter="10" class="row">
            <el-col class="col edb-col">
              <el-form-item :prop="`edbDataList.${index}.IndexCode`" 
              :rules="[{required:true,message:'指标ID不能为空',trigger:'blur'},
                        {validator:checkAge,trigger:'blur'}]">
                <el-input v-model.trim="item.IndexCode" placeholder="请输入指标ID"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="col classify-col">
              <el-form-item :prop="`edbDataList.${index}.BaseFromMysteelChemicalClassifyId`" 
              :rules="{required:true,message:'所属分类不能为空',trigger:'change'}">
                <el-cascader
                  class="classify-cascader"
                  :ref="'classifyCascader'+item.edbIndex"
                  v-model="item.BaseFromMysteelChemicalClassifyId"
                  :options="classifyOptions"
                  :key="item.edbIndex"
                  :props="{
                    label: 'ClassifyName',
                    value: 'BaseFromMysteelChemicalClassifyId',
                    children: 'Children',
                    emitPath: false,
                  }"
                  placeholder="请选择分类"
                />
              </el-form-item>
            </el-col>
            <img src="~@/assets/img/delete-minus-red.png" @click="delEdbItem(index)" v-if="edbForm.edbDataList.length>1" />
          </el-row>
          </div>
          <div class="add-box" @click="addEdbItem">
            <img src="~@/assets/img/add-quadrate-blue.png"/>
            <span>添加</span>
          </div>
        </el-form>
      </div>
      <div class="dia-bot">
        <el-button type="primary" style="margin-right: 20px" @click="saveHandle"
          >保存</el-button
        >
        <el-button type="primary" plain @click="cancelHandle">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { steelInterface } from "@/api/modules/thirdBaseApi";

  export default {
    props: {
      isOpenDialog: {
        type: Boolean,
      },
      classifyList: {
        type: Array,
      },
    },
    watch: {
      isOpenDialog(newval) {
        if (newval) {
          let classifyArr = _.cloneDeep(this.classifyList);
          this.filterNodes(classifyArr);
          this.classifyOptions = classifyArr;
        }
      },
    },
    data(){
      this.checkAge=(rule, value, callback) => {
        // 不能输入中文和空格
        let reg = /[\u4e00-\u9fa5]+|\s+/
        if(reg.test(value)){
          callback(new Error('不能输入中文和空格'))
        }else{
          callback()
        }
      }
      return{
        isAddLoading: false,
        classifyOptions:[],
        // edbIndex 仅前端使用的唯一标识
        edbForm:{edbDataList:[{edbIndex:1,IndexCode:'',BaseFromMysteelChemicalClassifyId:''}]},
        timer:null,
        emitParams:{},
        getAddBack:false
      }
    },
    methods:{
      saveHandle(){
        this.$refs.edbFormDataListRef.validate((valid)=>{
          if(valid){
            // console.log(this.edbForm.edbDataList);
            steelInterface.edbAdd({List:this.edbForm.edbDataList}).then(res=>{
                if (res.Ret !== 200) return;
                this.isAddLoading = true;
                // console.log(this.edbForm.edbDataList);
                let edbItem = this.edbForm.edbDataList.find(it => it.IndexCode.toUpperCase() == res.Data.IndexCode.toUpperCase())
                if(!edbItem){
                  edbItem=this.edbForm.edbDataList[0]
                }
                let edbIndexCurrent = edbItem?edbItem.edbIndex:0
                let selectClassifyNodes=this.$refs['classifyCascader'+edbIndexCurrent][0].getCheckedNodes()[0].path.map(it => it+'')
                this.emitParams={
                  code: res.Data.UniqueCode,
                  id: res.Data.BaseFromMysteelChemicalIndexId,
                  indexCode:res.Data.IndexCode,
                  selectClassifyNodes
                }
                this.getAddBack=true
                setTimeout(() => {
                  this.cancelHandle();
                  
                }, 5*60000);
              })
          
          }else{
            this.$message.error("指标信息请填写完整！")
            let errorElDom = this.$refs.edbFormDataListRef.fields.filter((item) => {
              return item.validateState === 'error';
            });
            let errorOffsetTops = errorElDom.map((item) => {
              return item.$el
            })
            // 滚动到指定节点
            errorOffsetTops[0].scrollIntoView({
                // 值有start,center,end，nearest
                block: 'start'
            })
          }
        })
      },
      /* 取消 */
      cancelHandle() {
        this.isAddLoading = false;
        this.edbForm={edbDataList:[{edbIndex:1,IndexCode:'',BaseFromMysteelChemicalClassifyId:''}]}
        this.$refs.edbFormDataListRef && this.$refs.edbFormDataListRef.resetFields();
        this.$emit("update:isOpenDialog", false);
        if(this.getAddBack){
          this.$emit("successCallback", this.emitParams);
          clearTimeout(this.timer)
          this.getAddBack=false
        }
      },
      // 递归改变第三级目录结构
      filterNodes(arr) {
        arr.length &&
          arr.forEach((item) => {
            item.Children &&
              item.Children.length &&
              this.filterNodes(item.Children);
            if (item.Level === 2) {
              delete item.Children;
            }
          });
      },
      addEdbItem(){
        this.$refs.edbFormDataListRef.validate(valid=>{
          if(valid){
            if(this.edbForm.edbDataList.length>=100){
              this.$message.warning('添加数量已达上限（上限100）！')
              return 
            }
            let lastItem = this.edbForm.edbDataList[this.edbForm.edbDataList.length-1]
            this.edbForm.edbDataList.push({
              edbIndex:lastItem?1+lastItem.edbIndex:1,
              IndexCode:'',
              BaseFromMysteelChemicalClassifyId:lastItem?lastItem.BaseFromMysteelChemicalClassifyId:''
            })
            this.$nextTick(()=>{
              // console.log(this.$refs.formBoxRef.scrollTop,this.$refs.formBoxRef.scrollHeight,'');
              this.$refs.formBoxRef.scrollTop = this.$refs.formBoxRef.scrollHeight
            })

          }else{
            // console.log(this.$refs.edbFormDataListRef.fields,'this.$refs.edbFormDataListRef.fields');
            let errorElDom = this.$refs.edbFormDataListRef.fields.filter((item) => {
              return item.validateState === 'error';
            });
            let errorOffsetTops = errorElDom.map((item) => {
              return item.$el
            })
            // 滚动到指定节点
            errorOffsetTops[0].scrollIntoView({
                // 值有start,center,end，nearest
                block: 'start'
            })
          }
        })
      },
      delEdbItem(index){
        this.edbForm.edbDataList.splice(index,1)
      }
    },
  }
</script>

<style lang="scss" scoped>
.dialog-main {
  padding: 0 35px;
  .form-box{
    max-height: 450px;
    overflow-y: auto;
    overflow-x: hidden;
    scroll-behavior: smooth;
  }
  .add-box{
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    margin-top: 10px;
    img{
      height: 18px;
      width: 18px;
      margin-right: 7px;
    }
    span{
      font-size: 14px;
      color: #0052D9;
    }
  }
  .row{
    .title-col{
      color: #333333;
    }
    .edb-col{
      width: 250px;
    }
    .classify-col{
      width: 382px;
    }
    img{
      height: 18px;
      width: 18px;
      margin: 10px 0 0 8px;
      cursor: pointer;
    }
  }
}

.dia-bot {
  margin: 52px 0 30px;
  display: flex;
  justify-content: center;
}
</style>
<style lang="scss">
.form-box{
  .el-form-item{
    margin-bottom: 18px;
  }
}
.col{
  .el-input{
    width: 100%;
    height: 38px;
    .el-input__inner{
      height: 38px;
    }
  }
  .classify-cascader{
    min-width: 100%;
  }
}
</style>