<!-- @desc:批量修改的组件  @auth:周兴  @time:2022/12/19 16:58 -->
<template>
  <Modal
    v-model="editBatchModal"
    ref="modal_editBatch"
    :title="vm.$t('editBatch')"
  >
    <DkForm name="dk-form" v-model="submitData" :labelWidth="80">
      <Row class="Row" style="width:500px" v-for="(item,itIndex) in formData" :key="itIndex">
        <Col span="24" class="col1">
          <!--       多选放大镜       -->
          <DkFormItem v-if="item.valueKind==='M-CHOICE'" :prop="item.valueFormat.code" style="width:100% ;">

            <SelectMagnifier v-model="submitData[item.valueFormat.code]"
                             :type="item.valueFormat.magnifierType" :doc-code="docCode"
                             :leafFlag="item.valueFormat.leafFlag" :ref="item.valueFormat.code"
            ></SelectMagnifier>
          </DkFormItem>
          <!--       单选放大镜       -->
          <DkFormItem v-if="item.valueKind==='S-SEARCH'" :prop="item.valueFormat.code" style="width:100% ;">
            <SelectMagnifier v-model="submitData[item.valueFormat.code]" :multiple="false"
                             :type="item.valueFormat.magnifierType" :doc-code="docCode"
                             :leafFlag="item.valueFormat.leafFlag" :ref="item.valueFormat.code"

            ></SelectMagnifier>
          </DkFormItem>
          <!--       单选下拉       -->
          <DkFormItem v-if="item.valueKind==='S-CHOICE'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <SelectPop :labelKey="item.valueFormat.labelKey" :valueKey="item.valueFormat.valueKey" :multiple="false"
                       v-model="submitData[item.valueFormat.code]"
                       :options="item.valueFormat.data" :ref="item.valueFormat.code"
                       :placeholder="vm.$t('inputWords',{'search-name':item.itemName})"/>
          </DkFormItem>
          <!--       文本       -->
          <DkFormItem v-if="item.valueKind==='STR'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <InputPop v-model="submitData[item.valueFormat.code]" :ref="item.valueFormat.code" size="small"
                      :placeholder="vm.$t('inputWords',{'search-name':item.itemName})"/>
          </DkFormItem>
          <!--       多行文本       -->
          <DkFormItem v-if="item.valueKind==='TXT'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <InputPop v-model="submitData[item.valueFormat.code]" :ref="item.valueFormat.code" size="small" textareaFlag
                      :placeholder="vm.$t('inputWords',{'search-name':item.itemName})"/>
          </DkFormItem>
          <!--       数值文本       -->
          <DkFormItem v-if="item.valueKind==='NUM'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <InputNumberPop v-model="submitData[item.valueFormat.code]" :ref="item.valueFormat.code" size="small"
                            :placeholder="vm.$t('inputWords',{'search-name':item.itemName})" :digits="item.valueFormat.digits"/>
          </DkFormItem>
          <!--       日期       -->
          <DkFormItem v-if="item.valueKind==='DATE'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <DatePicker type="date" clearable size="small" transfer placement="bottom-end"
                        v-model="submitData[item.valueFormat.code]" :editable="false"
                        :placeholder="vm.$t('inputWords',{'search-name':item.itemName})" style="width:100%"></DatePicker>
          </DkFormItem>
          <!--       开关       -->
          <DkFormItem v-if="item.valueKind==='BOOL'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <i-switch v-model="submitData[item.valueFormat.code]" size="small">
              <span slot="open"></span>
              <span slot="close"></span>
            </i-switch>
          </DkFormItem>
        </Col>
      </Row>
      <!--key需要加上+formData.length，不然会跟上面的冲突-->
      <Row class="Row" style="width:500px" v-for="(it,itIndex1) in Math.ceil(formDataBool.length/colCount + 0.000000001)" :key="itIndex1+formData.length">
        <Col span="8" class="col1" v-for="(item,index) in formDataBool.slice(itIndex1*colCount,(itIndex1*colCount) + colCount) "  :key="index">
          <!--       开关       -->
          <DkFormItem v-if="item.valueKind==='BOOL'" :prop="item.valueFormat.code" style="width:100% ;" :label="item.itemName">
            <i-switch v-model="submitData[item.valueFormat.code]" size="small">
              <span slot="open"></span>
              <span slot="close"></span>
            </i-switch>
          </DkFormItem>
        </Col>
      </Row>
    </DkForm>
    <div slot="footer" style="width:100%;border:none;">
      <DkButton ref="save" type="primary" @click="save">{{ vm.$t('save') }}</DkButton>
      <DkButton ref="close" @click="close">{{ vm.$t('close') }}</DkButton>
    </div>
  </Modal>
</template>

<script>

import {button as buttonList} from "@/locale/lang/zh-CN";

export default {
  name: "ModalBatchEdit",
  data() {
    const vm = window.vm;
    return {
      vm: vm,
      documentKeyDownContent: Object,
      docCode:'',
      editBatchModal:false,
      formData: [],
      formDataBool: [],
      setFlag: true,
      submitData:{},
      colCount: 3,
      // 第一个元素
      firstFormData : {},
      // cancelFunc: () => {
      // },//取消回调
      okFunc: () => {
      }//确定回调
    }
  },
  methods: {
    /**
     * @desc   : 监听全局键盘按钮按下的事件
     * @author : 周兴
     * @date   : 2022/3/4 16:57
     */
    addKeyBoardEvent() {
      let code = 0
      let self = this
      this.documentKeyDownContent = document.onkeydown;
      document.onkeydown = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        // alt：code = 18
        if (key === 18) {
          code = 18
        }

        // Q：code = 81 查询
        let btList = Object.values(self.$config.button);
        btList.forEach(forIt => {
          if (code === 18 && forIt.hotKey?.toLowerCase() === e.key.toLowerCase()) {
            e.returnValue = false
            if (self.$refs[forIt.name]) {
              self.$refs[forIt.name].$el.click()
            }
          }
        })
      }
      // 监听全局键盘按钮松开的事件
      document.onkeyup = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        if (key === 18) {
          code = 0
        }
        // 一秒钟失效，避免因为按了alt+tab之后再回来，按其他什么英文字母都不好使了的问题
        setTimeout(() => {
          code = 0
        }, 1000)
      }
    },
    /**
     * @desc   : 聚焦
     * @author : 周兴
     * @date   : 2022/3/27 13:20
     */
    focus(){
      // 控制光标放到第一个元素上
      if(this.formData){
        let first = this.formData[0]
        // 文本
        if(first.valueKind === this.$config.docUserInput.str
          || first.valueKind === this.$config.docUserInput.sChoice){
          this.$nextTick(()=>{
            // console.log('first',this.$refs, first.valueFormat.code,this.$refs[first.valueFormat.code])
            this.$refs[first.valueFormat.code][0].focus();
          })
        }
        // 数值
        else if(first.valueKind === this.$config.docUserInput.num){
          this.$nextTick(()=>{
            // console.log('first',this.$refs, first.valueFormat.code,this.$refs[first.valueFormat.code])
            this.$refs[first.valueFormat.code][0].$refs['inputNumber'].focus();
          })
        }
        // 日期
        else if(first.valueKind === this.$config.docUserInput.dateRange){
          this.$nextTick(()=>{
            this.$refs[first.valueFormat.code][0].isFocused = true;
          })
        }
        // 下拉选择
        else if(first.valueKind === this.$config.docUserInput.mSearch
          || first.valueKind === this.$config.docUserInput.sSearch){
          this.$nextTick(()=>{
            this.$refs[first.valueFormat.code][0].$refs['select'].focus();
          })
        }
      }
    },
    /**
     * @desc   : 设置查询条件
     * @author : 周兴
     * @date   : 2022/3/3 17:10
     */
    setForm() {
      // 从数据库中读取
      if (this.setFlag) {
        let param = {}
        param.docCode = this.docCode
        param.itemType = 1
        param.isBatchUpdate = true
        DocItemService.getDocItem(param).then(res => {
          if (res.code === 200) {
            this.formData = res.data
            // 如果有多个开关，那么需要放在formDataBool进行排列，一行3个
            let formDataBool = []
            this.focus()// 光标放在第一个控件上
            this.formData.forEach(it => {
              // 如果是下拉菜单要获取数据
              if ( it.valueKind === 'S-CHOICE'
                && it.valueFormat.type === 'active') {
                // console.log('@/api/',it.valueFormat)
                let service = require('@/api/' + it.valueFormat.api.service).default
                let param = it.valueFormat.api.params
                param.soId = vm.$store.state.user.soId
                service[it.valueFormat.api.methods](param).then(res => {
                  let data = {...res}
                  it.valueFormat.api.result.forEach(resultIt => {
                    data = data[resultIt]
                  })
                  it.valueFormat.data = data
                })
              }
              else if(it.valueKind === 'S-SEARCH' || it.valueKind === 'M-SEARCH'){
                // 如果后台没有leafFlag,
                if(!it.valueFormat.leafFlag){
                  it.valueFormat.leafFlag = false;
                }
              }
              // 数值
              else if(it.valueKind === 'NUM'){
                // 如果后台没有precision,默认为0
                if(!it.valueFormat.digits){
                  it.valueFormat.digits = 0;
                }
              }
              // 开关
              else if(it.valueKind === 'BOOL'){
                formDataBool.push(it);
              }
            })
            // 如果开关是多个就要赋值到formDataBool
            if(formDataBool.length> 1){
              this.formData = this.formData.filter(it=>{return it.valueKind !== 'BOOL'}).map(it=>{return it});
              this.formDataBool = formDataBool;
            }
          }
        })
      } else {
        // 不从数据库读取
        // this.formData = [...this.value]
        let submitData = {}
        // 设置label
        this.formData.forEach(it => {
          it.itemName = vm.$t(it.valueFormat.code)
          submitData[it.valueFormat.code] = null
          // submitData.push(item)
        })
      }
    },
    /**
     * @desc   : 保存
     * @author : 周兴
     * @date   : 2022/3/25 20:16
     */
    save() {
      // 校验，至少要修改一项
      if(!this.check()){
        this.focus(); // 光标回到第一个元素
        this.$Message.warning(vm.$t('W_017'))
        return;
      }
      this.editBatchModal = false;
      this.okFunc(this.submitData)
    },
    /**
     * @desc   : 关闭
     * @author : 周兴
     * @date   : 2022/3/27 20:23
     */
    close(){
      this.editBatchModal = false
      // this.cancelFunc()
    },
    /**
     * @desc   : 批量修改至少输入或选择一项 判断
     * @author : 周兴
     * @date   : 2022/3/27 20:25
     */
    check(){
      let checkFlag = false
      let keys = Object.keys(this.submitData)
      // console.log('t',keys)
      for (let i = 0 ;i< keys.length;i++){
        // console.log('t',keys[i])
        if(!this.isNull(keys[i])){
          checkFlag = true;
          break;
        }
      }
      return checkFlag;
    },
    /**
     * @desc   : 是否为NULL
     * @author : 姜永辉
     * @date   : 2022/3/23 10:39
     */
    isNull(value) {
      if (value == null || typeof (value) == 'undefined' ||
        value === undefined || value == '') {
        return true
      }
      return false
    },
  },
  mounted() {
    this.addKeyBoardEvent()   // 增加快捷键
  },
  watch: {
    editBatchModal(n, o) {
      if (!n) {
        //回复快捷键
        document.onkeydown = this.documentKeyDownContent;
      }
    }
  },
  created() {
    this.setForm()     // 设置窗体项目
  }
}
</script>

<style scoped>
.col1 {
  margin-bottom: 3px;
}
</style>
