<template>
 <div>
   <div>
     <el-breadcrumb separator="/" class="my-breadcrumb">
       <el-breadcrumb-item>数据质检 </el-breadcrumb-item>
       <el-breadcrumb-item>质检任务</el-breadcrumb-item>
     </el-breadcrumb>
   </div>
   <div class="back" @click="$emit('changeOperation','',{})"><span class="fa fa-reply cur-po " >返回</span></div>
   <div class="detail-main">
     <div class="block">
       <div class="my-b-title">基本信息</div>
      <div class="form"> <diy-el-form v-model:model-form="forms" :forms="formConfig1"/></div>
     </div>
   </div>
   <div class="detail-main">
     <div class="block">
       <div class="my-b-title">质检项信息</div>
       <div>
         <div class="my-search-div">
           <el-input v-model="keyWord"/>
         </div>
         <my-table
           :filter-meothod="row => row.NAME.includes(keyWord)"
           :has-operation="true"
           border
           :is-height-equal-max-height="true"
           :page-size="6"
           :headers="qualityCheckTaskDetailTableHeader"
         :table-data="qualityCheckTableData"

         >
           <template #QUALITY_RULE="{data}">
             {{getQualityRule(data.QUALITY_RULE,data)}}
           </template>
           <template #operation="{data}">
            <el-button type="danger" @click="changeState(data,'禁用')" :disabled="operationType === 'detail'" v-if="data.STATENAME === '启用'">禁用</el-button>
            <el-button type="info" @click="changeState(data,'启用')" :disabled="operationType === 'detail'" v-else>启用</el-button>
           </template>
         </my-table>
         <div class="m-s">显示第 1 到第 {{totalCount}} 条记录，总共 {{totalCount}} 条记录</div>
       </div>
     </div>
     <div class="detail-operation-btn" v-if="operationType !== 'detail'">
       <el-button :icon="Refresh" @click="saveOrRefsh">运行</el-button>
       <el-button :icon="Select" @click="saveOrRefsh">保存</el-button>
       <el-button :icon="Close" @click="$emit('changeOperation','')">返回</el-button>
     </div>
   </div>

 </div>
</template>

<script>
import {onBeforeMount, ref, watch} from "vue";
import {qualityCheckTaskDetailBaseForm} from "@/data/all-forms";
import DiyElForm from "@/components/common/DiyElForm.vue";
import MyTable from "@/components/common/MyTable.vue";
import {qualityCheckTaskDetailTableHeader} from "@/data/all-table-header";
import {getQualityDetailTableData, saveQualityDetailSave} from "@/service/data-quelity-check/quality-check-task";
import {elAlert, handleMes, showMessage} from "@/unit/element-ui/tip";
import {Close, Refresh, Select} from "@element-plus/icons-vue";
import {isEmptyCheck} from "@/unit/validate";
import {useRootStore} from "@/stores/useStore";

export default {
  name: "QualityCheckTaskDetail",
  computed: {
    Refresh() {
      return Refresh
    },
    Close() {
      return Close
    },
    Select() {
      return Select
    }
  },
  components: {MyTable, DiyElForm},
  setup(props,{emit}) {
    const keyWord = ref('')
    function getConfigName(type, pcode) {
      let  json_configs
      //json_configs
      if (json_configs == null) {
        let para_configs = useRootStore().paraArr
        for (var i = 0 ; i < para_configs.length ; i++) {
          if (json_configs == null || isEmptyCheck(json_configs[para_configs[i]["PARA_CODE"]])) {
            if (json_configs == null) {
              json_configs = {};
            }
            var code = para_configs[i]["CODE"];
            var name = para_configs[i]["NAME"];
            json_configs[para_configs[i]["PARA_CODE"]] = {};
            json_configs[para_configs[i]["PARA_CODE"]][code] = name;
          } else {
            var code = para_configs[i]["CODE"];
            var name = para_configs[i]["NAME"];
            json_configs[para_configs[i]["PARA_CODE"]][code] = name;
          }
        }
      }
      return json_configs[type][pcode] == null || json_configs[type][pcode] == "" ? pcode : json_configs[type][pcode];
    }
    function getQualityRule (value,row) {
      if (value != '[]' && value != '' && value != undefined) {
        var rule_value = JSON.parse(value);
        var rule_string = '';
        switch (row.CODE) {
          case "C0001":
            rule_string = '是否非空：'
            rule_string += rule_value[0].NOT_NULL == '1' ? '是' : '否';
            return rule_string;
          case "C0002":

            rule_string = getConfigName('90', rule_value[0].CHACK_TYPE) + ":" + rule_value[0].CHACK_VALUE + ";";
            return rule_string;
          case "C0003":
            rule_string = '是否唯一：'
            rule_string += rule_value[0].ONLY == '1' ? '是' : '否';
            return rule_string;
          case "C0004":
            getConfigName('92', rule_value[0].DATA_FORMAT);;
            rule_string += getConfigName('92', rule_value[0].DATA_FORMAT) + ";";
            return rule_string;
          case "C0005":
            getConfigName('90', rule_value[0].CHACK_TYPE);
            getConfigName('91', rule_value[0].DATA_TYPE);;
            rule_string += getConfigName('91', rule_value[0].DATA_TYPE) + ":" + getConfigName('90', rule_value[0].CHACK_TYPE) + ":" + rule_value[0].VALUE + ";";
            return rule_string;
          case "C0006":

            return rule_string;
          case "C0007":
            for (var i = 0; i < rule_value.length; i++) {
              rule_string +=  rule_value[i].VALUE + ";";
            }
            if (rule_string.length > 13) {
              return "<div title='" + rule_string + "' href='#' style='cursor:pointer;text-decoration: none;'>" + rule_string.trim().substr(0, 13) + "..." + "</div>";
            } else {
              return rule_string;
            }
          case "C0009":
            rule_string = '数据字典'
            return rule_string;
          case "C0010":
            rule_string = '文件验证';
            return rule_string;
          case "C0011":
            rule_string = '截取验证';
            return rule_string;
          case "C0013":
            rule_string = '判断节点是否合法';
            return rule_string;
        }
      }
    }
    function changeState(data,state) {
     data.QYZT = '已' + state

     data.STATENAME = state
      showMessage({
        type:'success',
        message:data.QYZT
      })
    }
    const totalCount= ref(0)
    function saveOrRefsh(){
      if (!(qualityCheckTableData.value.length > 0)){
        elAlert('请先配置质检规则')
        return
      }
      let EXEC_TIME
      if (forms.value.cycle === '0'){
        //  周期执行
        if (forms.value.frequency === '每年'){
          EXEC_TIME = [forms.value.month,forms.value.day,forms.value.time].join('-')

        } else if (forms.value.frequency === '月'){
          EXEC_TIME = [forms.value.day,forms.value.time].join('-')

        } else if (forms.value.frequency === '周'){
          EXEC_TIME = [forms.value.day,forms.value.time].join('-')

        }else if (forms.value.frequency === '日'){
          EXEC_TIME = [forms.value.time].join('-')

        }else if (forms.value.frequency === '时'){
          EXEC_TIME = [forms.value.time].join('-')
        }
      }
      else if (forms.value.cycle === '1'){
        EXEC_TIME = [forms.value.singleYear,forms.value.singleMonth,forms.value.singleDay,forms.value.singleTime].join('-')

      }
      let params = {
        main:{
          UUID:props.currentOpObj.UUID,
          CATALOG_CODE:props.currentOpObj.CATALOG_CODE,
          TABLE_SPACE:'',
          TABLE_NAME:forms.value.KBGL_TABLENAME,
          "STATE": "2",
          ORDER_NUM:forms.value.ORDER_NUM,
          EXEC_CYCLE:forms.value.cycle,
          CYCLE_CLASS:forms.value.frequency,
          EXEC_TIME:EXEC_TIME,
          SPACE_TIME:'',
          SPACE_NUM:'',
          IS_RETRY:'0',
          "IS_EXEC": "0",

        },
        rules:qualityCheckTableData.value.map(i => {
          return {
            ...i,
            STATE:i.STATENAME
          }
        })
      }
      saveQualityDetailSave(params).then(res => {
        handleMes(res,() => {
          emit('changeOperation','')
        })
      })
    }
    const forms = ref({

    })
    const qualityCheckTableData = ref([

    ])
    const formConfig1 = ref({...qualityCheckTaskDetailBaseForm()})
    onBeforeMount(() => {
      if (props.operationType !== 'add'){
        forms.value = {
          ...props.currentOpObj,
          ORDER_NUM:props.currentOpObj.ORDER_NUM?props.currentOpObj.ORDER_NUM + '' : '',
          cycle:props.currentOpObj.EXEC_CYCLE,
          frequency:props.currentOpObj.CYCLE_CLASS,
        }
        const splitA = (forms.value.EXEC_TIME || '').split('-')
        if (splitA.length > 0){
          if (forms.value.cycle === '0'){
            //  周期执行
           if (forms.value.frequency === '每年'){
             forms.value.month = splitA[0] || ''
             forms.value.day = splitA[1] || ''
             forms.value.time = splitA[2] || ''
           } else if (forms.value.frequency === '月'){

              forms.value.day = splitA[0] || ''
              forms.value.time = splitA[1] || ''
            } else if (forms.value.frequency === '周'){

             forms.value.day = splitA[0] || ''
             forms.value.time = splitA[1] || ''
           }else if (forms.value.frequency === '日'){
             forms.value.time = splitA[0] || ''
           }else if (forms.value.frequency === '时'){
             forms.value.time = splitA[0] || ''
           }
          }
          else if (forms.value.cycle === '1'){
            forms.value.singleYear = splitA[0] || ''
            forms.value.singleMonth = splitA[1] || ''
            forms.value.singleDay = splitA[2] || ''
            forms.value.singleTime = splitA[3] || ''
          }
        }
        getQualityDetailTableData({
          pageIndex:1,
          pageSize:2000,
          CODE:props.currentOpObj.CATALOG_CODE
        }).then(res => {
          qualityCheckTableData.value = (res.msg[0].Rows||[]).map(i => {
            return {
              ...i,
              STATENAME:i.STATE === '1'?'启用':'禁用',
              QYZT:i.STATE === '1'?'已启用':'已禁用'
            }
          })
          totalCount.value = res.msg[0].TotalRowCount

        })
      }
    })
    watch(() =>forms.value.cycle,(val) => {
      const beforeForm =  qualityCheckTaskDetailBaseForm().formItemsArr.slice(0,3)
      let findItemCycle = formConfig1.value.formItemsArr.find(i => i.modelValue === 'cycle')
     let findAdd = findItemCycle.options.find(i => i.value === val)
      if (findAdd){
        formConfig1.value.formItemsArr  =[...beforeForm,...findAdd.forms]
      }else {
        formConfig1.value.formItemsArr = beforeForm
      }
      let val2 = forms.value['frequency']
      if (val2){
        let findFrequencyIndex = formConfig1.value.formItemsArr.findIndex(i => i.modelValue === 'frequency')
        console.log('findFrequencyIndex',findFrequencyIndex)
        if (findFrequencyIndex === -1){
          return
        }

        let findAdd = formConfig1.value.formItemsArr[findFrequencyIndex].radioArr.find(i => i.value === val2)
         if (!findAdd) {
           return;
         }
        formConfig1.value.formItemsArr = [...formConfig1.value.formItemsArr.slice(0,findFrequencyIndex + 1),...findAdd.forms]
      }
      // if(val === '0'){
      // // 周期执行
      //   forms.value['frequency'] = ''
      // }
    })
    watch(() => forms.value['frequency'],(val) => {
      if (val){
        let findFrequencyIndex = formConfig1.value.formItemsArr.findIndex(i => i.modelValue === 'frequency')
        console.log('findFrequencyIndex',findFrequencyIndex)
        if (findFrequencyIndex === -1){
          return
        }

        let findAdd = formConfig1.value.formItemsArr[findFrequencyIndex].radioArr.find(i => i.value === val)
        if (!findAdd) {
          return;
        }
        formConfig1.value.formItemsArr = [...formConfig1.value.formItemsArr.slice(0,findFrequencyIndex + 1),...findAdd.forms]
      }
    })
    return {
      forms,
      formConfig1,
      qualityCheckTableData,
      qualityCheckTaskDetailTableHeader,
      saveOrRefsh,
      totalCount,
      changeState,
      getQualityRule,
      keyWord
    }
  },
  props:{
    currentOpObj:{

    },
    operationType:{

    }
  }
}
</script>

<style scoped lang="scss">
.detail-main{
  .m-s{
    padding-bottom: 20px;
  }
  .form{
    max-width: 600px;
  }
  padding: 0 20px;

}
</style>
