<script>
import {searchCodeItemAllDefsSeq, searchCodeItemDefs, searchCodeItemDefsSeq} from "../../../api/code/codeItemDef";
import {searchCodeGenerationItemValueList} from "../../../api/code/codeItemValue";
import {codeNoGenerate, saveDrawing} from "../../../api/code/codeDrawing";
import dayjs from "dayjs";
import {queryCodeErpPartNo, searchCodeParameterById} from "../../../api/code/codeParameterDef";
import itemValue from "./item/itemValue.vue";

export default {
  name: "CodeGeneration",
  computed: {
    itemValue() {
      return itemValue
    },
    showConditionName() {
      return (val) => {
        if (val && val.length > 0){
          return val[0].conditionName
        }
        return ''
      };
    }
  },
  data(){
    return {
      codeItemDefs: [],
      searchModel:{
        drawingNo: "",
        drawingNoNew: "",
        drawingDesc: "",
        erpPartNo: "",
        erpPartDesc: "",
        remark: "",
        seqFlag: "N",
      },
      codeItemTypes: [],
      codeItemValues: [],
      width: 800,
      loadingIndex:-1,
      checkCodeFlag:'N',
      getCodeNoLoading: false,
      saveCodeLoading: false,
      rules:{
        drawingNo: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        erpPartNo: [{ required: true, message: '请输入IFS Part No', trigger: 'blur' }],
        erpPartDesc: [{ required: true, message: '请输入IFS Part Descriptions', trigger: 'blur' }],
        drawingDesc: [{ required: true, message: '请输入编码描述', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入编码备注', trigger: 'blur' }],
      }
    }
  },
  created() {
    this.searchCodeItemDefs();
    this.searchCodeParameterById();
  },
  beforeDestroy() {

  },
  methods:{
    searchCodeItemDefs(){
      let params = {
        site:this.$store.state.user.site,
      }
      this.codeItemTypes = [];
      this.codeItemValues = [];
      searchCodeItemAllDefsSeq(params).then(({data})=>{
        if (data && data.code === 0){
          this.codeItemDefs = data.rows;
          for (let i = 0; i < this.codeItemDefs.length; i++) {
            let arr = this.codeItemDefs[i].itemType.split('或');
            this.codeItemTypes[i] = arr[0]
            this.codeItemValues[i] = undefined
          }
        }else {
          this.$message.warning(data.msg);
        }
      }).catch((error) => {
        this.$message.error(error);
      });
    },
    changeCodeItemType(index){
      this.$set(this.codeItemValues, index, undefined)
      this.changeRowCodeItemValue(index)
    },
    getCodeNoBtn(){
      if (this.codeItemDefs.length === 0){
        this.showAlert("尚未设置编码规则！请先到“编码组成元素定义”中定义！")
        return;
      }
      // this.getCodeNoLoading = true;
      let params = [];
      // 验证是否都输入
      for (let i = 0; i < this.codeItemDefs.length; i++) {
        if (!this.codeItemValues[i] && !(this.codeItemDefs[i].itemType.includes('流水号') && this.codeItemTypes[i] === '流水号')){
          this.showAlert(`元素${this.codeItemDefs[i].itemDesc}的值为空`);
          this.getCodeNoLoading = false;
          return;
        }
        if (this.codeItemDefs[i].itemType.includes('手工') && this.codeItemTypes[i] === '手工' && this.codeItemValues[i].length > this.codeItemDefs[i].bits ){
          this.showAlert(`元素${this.codeItemDefs[i].itemDesc}的值长度不正确,编码位数应为${this.codeItemDefs[i].bits}`)
          this.getCodeNoLoading = false;
          return;
        }
        // let paramsData = {
        //   codeItemDef: {...this.codeItemDefs[i]},
        //   currentValueNo:"",
        //   currentSeqValueNo:"",
        //   currentCodeDesc:"",
        //   currentCodeRemark:"",
        //   codeNo:"",
        //   codeHasSeq:"N",
        //   hasSeqCount:0,
        // };
        // if (this.codeItemDefs[i].itemType.includes('手工') && this.codeItemTypes[i] === '手工'){
        //   paramsData.currentValueNo = this.codeItemValues[i];
        //   paramsData.currentSeqValueNo = `{${paramsData.currentValueNo}}`
        // }else if (this.codeItemDefs[i].itemType.includes('选择') && this.codeItemTypes[i] === '选择'){
        //   // 寻找 简码
        //   paramsData.currentValueNo = this.getValueNo(this.codeItemDefs[i].itemValues,this.codeItemValues[i]).valueNo
        //   paramsData.currentSeqValueNo = `{${paramsData.currentValueNo}}`
        // }else {
        //   paramsData.codeHasSeq = "Y";
        //   paramsData.hasSeqCount++;
        // }
        let paramsData = {
          ...this.codeItemDefs[i],
        }
        if (this.codeItemDefs[i].itemType.includes('手工') && this.codeItemTypes[i] === '手工'){
            paramsData.value = this.codeItemValues[i];
            paramsData.itemType = '手工'
          }else if (this.codeItemDefs[i].itemType.includes('选择') && this.codeItemTypes[i] === '选择'){
            // 寻找 简码
            paramsData.name = this.codeItemDefs[i].itemValues[0].conditionName
            paramsData.value = this.getValueNo(this.codeItemDefs[i].itemValues,this.codeItemValues[i]).valueNo
            paramsData.label = this.getValueNo(this.codeItemDefs[i].itemValues,this.codeItemValues[i]).itemValue
            paramsData.itemType = '选择'
          }else if (this.codeItemDefs[i].itemType.includes('流水号') && this.codeItemTypes[i] === '流水号'){
            paramsData.itemType = '流水号'
          }
        params.push(paramsData)
      }
      this.codeNoGenerate(params)
    },
    codeNoGenerate(params){
      codeNoGenerate(params).then(({data})=>{
        if (data && data.code === 0){
          this.searchModel = {
            ...this.searchModel,
            drawingNo: data.row.drawingNo,
            drawingDesc: data.row.drawingDesc,
            remark: data.row.remark,
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error) => {
        this.$message.error(error);
      })
    },
    getValueNo(arr,valueItemNo){
      // 寻找 简码
      return arr.find(item=>item.valueItemNo === valueItemNo)
    },
    showAlert(msg){
      this.$alert(msg, '提示', {
        confirmButtonText: '确定',
      });
    },
    changeCodeItemValue(index,val){
      let codeItemDef = this.codeItemDefs[index]
      if (val === true && codeItemDef.itemByCondition === 'Y'){
        if (index === 0){
          this.$message.warning("请先检查该元素的定义可选值设置中是否都已经维护了条件!")
        }else {
          // 请求后台，让后台校验参数/获得数据
          let codeItemDefs = [];
          for (let i = 0; i <= index; i++) {
            let codeItemDef = {
              ...this.codeItemDefs[i],
              value:this.codeItemValues[i]
            }
            codeItemDefs.push(codeItemDef)
          }
          this.searchCodeGenerationItemValueList(codeItemDefs,index)
        }
      }
    },
    searchCodeGenerationItemValueList(arr,index){
      if (arr.length === 0){
        return;
      }
      this.loadingIndex = index
      this.codeItemDefs[index].itemValues = []
      this.$set(this.codeItemDefs, index, {...this.codeItemDefs[index]})
      searchCodeGenerationItemValueList(arr).then(({data})=>{
        if (data && data.code === 0){
          let itemDefs = {...this.codeItemDefs[index], itemValues: data.rows}
          this.$set(this.codeItemDefs, index, itemDefs)
        }else {
          this.$refs[`codeItemValue${index}`][0].blur();
          this.$alert(data.msg, '提示', {
            confirmButtonText: '确定',
          });
        }
        this.loadingIndex = -1
      }).catch((error)=>{
        this.$message.error(error);
        this.loadingIndex = -1
      })
    },
    changeRowCodeItemValue(index){
      // 值发生变化清空后续所有参数
      if (this.checkCodeFlag === 'Y'){
        for (let i = index+1; i < this.codeItemDefs.length; i++) {
          if (this.codeItemDefs[i].itemByCondition === 'Y'){
            this.$set(this.codeItemValues, i, undefined)
          }
        }
      }
    },
    saveDrawing(){
      this.$refs.drawingForm.validate((valid,obj)=>{
        if (valid){
          let params = {
            ...this.searchModel,
            site:this.$store.state.user.site,
            creator:this.$store.state.user.name,
            createDate:dayjs().format('YYYY-MM-DD HH:mm:ss'),
          }
          this.saveCodeLoading = true;
          saveDrawing(params).then(({data})=>{
            if (data && data.code === 0){
              this.$alert(`成功获取并保存了编码${this.searchModel.drawingNo}`, '提示', {
                confirmButtonText: '确定',
              });
              Object.keys(this.searchModel).forEach(key => {
                this.$set(this.searchModel, key, '')
              })
              for (let i = 0; i < this.codeItemDefs.length; i++) {
                this.$set(this.codeItemValues, i, undefined)
              }
              this.saveCodeLoading = false;
              this.searchCodeItemDefs();
            }else {
              this.saveCodeLoading = false;
              this.$message.warning(data.msg)
            }
          }).catch((error) => {
            this.$message.error(error);
          })
        }else {
          let i = 1;
          for (let key in obj) {
            this.$message.error(`${obj[key][0].message}`);
            if (i === 1){
              return
            }
            i++;
          }
        }
      })
    },
    searchCodeParameterById(){
      searchCodeParameterById(11).then(({data})=>{
        if (data && data.code === 0){
          this.checkCodeFlag = data.row.parameterValue
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleBlurErpPartNo(){
      let params = {
        erpPartNo:this.searchModel.erpPartNo,
      }
      queryCodeErpPartNo(params).then(({data})=>{
        if (data && data.code === 0){
          if (data.row){
            this.searchModel.erpPartDesc = data.row.partDesc
          }else {
            this.searchModel.erpPartDesc = ''
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    }
  },
  watch:{
    'searchModel.erpPartNo'(newVal,oldVal){
      this.searchModel.erpPartNo = newVal.toUpperCase()
    }
  }
}
</script>

<template>
<div>
  <el-form :model="searchModel" ref="drawingForm" :rules="rules" label-position="top">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="编码:" prop="drawingNo" :show-message="false">
          <el-input readonly v-model="searchModel.drawingNo"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="1.5">
        <el-form-item label=" ">
          <el-button type="primary" :loading="getCodeNoLoading" @click="getCodeNoBtn">获取编码</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="1.5">
        <el-form-item label=" ">
          <el-button type="primary" :loading="saveCodeLoading" @click="saveDrawing">占有编码</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="IFS Part No" prop="erpPartNo" :show-message="false">
          <el-input v-model="searchModel.erpPartNo" @blur="handleBlurErpPartNo"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="IFS Part Description" prop="erpPartDesc" :show-message="false">
          <el-input v-model="searchModel.erpPartDesc" disabled></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="编码描述:">
          <el-input readonly v-model="searchModel.drawingDesc"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注">
          <el-input readonly v-model="searchModel.remark"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div style="margin-top: 10px;border-top: 1px solid #ccc;padding-top: 10px;height: 680px;overflow-y: auto;width: 100%" >
    <el-form label-position="left" label-width="100px">
      <el-form-item :label="`${item.itemDesc}:`" v-for="(item, index) in codeItemDefs" :key="index" style="margin-bottom: 10px">
        <div v-if="item.itemType.includes('或')" style="width: 240px;display: inline-block">
          <el-radio-group v-model="codeItemTypes[index]" @change="changeCodeItemType(index)">
            <el-radio v-if="item.itemType.includes('选择')" label="选择">选择</el-radio>
            <el-radio v-if="item.itemType.includes('手工')" label="手工">手工</el-radio>
            <el-radio v-if="item.itemType.includes('流水号')" label="流水号">流水号</el-radio>
          </el-radio-group>
        </div>
        <div style="display: inline-block;" :style="{width: `${item.itemType.includes('或')?(width-240-205):(width-200)}px`}">
          <el-select
            :loading="loadingIndex === index"
            :ref="`codeItemValue${index}`"
            clearable v-if="codeItemTypes[index] === '选择'"
            filterable
            @change="changeRowCodeItemValue(index)"
            @visible-change="(val)=>changeCodeItemValue(index,val)"
            style="width: 100%;"
            v-model="codeItemValues[index]">
            <el-option :value="val.valueItemNo" :label="val.itemValue" v-for="(val , i) in item.itemValues" :key="i"></el-option>
          </el-select>
          <el-input v-if="codeItemTypes[index] === '手工'" placeholder="请输入" v-model="codeItemValues[index]"></el-input>
          <el-input v-if="codeItemTypes[index] === '流水号'" disabled v-model="codeItemValues[index]"></el-input>
        </div>
        <div style="display: inline-block" v-if="showConditionName(item.itemValues) !== ''">
          <span v-if="">(</span><span>{{showConditionName(item.itemValues)}}</span><span>)</span>
        </div>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<style scoped>

</style>
