<template>
  <a-modal
    :title="modalTitle"
    :width="1100"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <div :style="{ marginBottom: '16px' }">
      <a-form layout="inline">
        <a-row :gutter="24">

          <a-col :span="3">
            <a-button type="primary" icon="plus" @click="add" :loading="addSbConfirmLoading">
              新增设备
            </a-button>
          </a-col>

          <a-col :span="3">
            <a-button type="primary" icon="plus" @click="changeProjectQuantity" >
              批量修改
            </a-button>
          </a-col>

          <a-col :span="8">
            <a-form-item label="作业名称">
              <a-tree-select
                @change="projectQuantityChange"
                style=" width: 150px"
                v-model="projectQuantityId"
                :treeNodeFilterProp="'title'"
                placeholder="请选择作业"
                :allow-clear="true"
                :show-search="true"
                :replaceFields="{children:'children', title:'title', key:'key', value: 'id' }"
                :tree-default-expand-all="true"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :treeData="projectQuantityList"
              />
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item label="作业位置">
              <!-- 解决校验问题 -->
              <a-input-group compact>
                <a-form-item>
                  <a-input-number
                    style=" width: 80px; text-align: center"
                    :min="0"
                    :step="0.001"
                    :formatter="BaseTool.Amount.formatter"
                    :parser="BaseTool.Amount.parser"
                    v-model="projectQuantityStart"
                    placeholder="起始值" />
                </a-form-item>
                <a-form-item>
                  <a-input
                    style=" width: 30px; border-left: 0; pointer-events: none; backgroundColor: #fff"
                    value="~"
                    disabled
                  />
                </a-form-item>
                <a-form-item>
                  <a-input-number
                    style="width: 80px; text-align: center; border-left: 0"
                    :min="0"
                    :step="0.001"
                    :formatter="BaseTool.Amount.formatter"
                    :parser="BaseTool.Amount.parser"
                    v-model="projectQuantityEnd"
                    placeholder="结束值"
                  />
                </a-form-item>
                <a-form-item v-show="false">
                  <a-input-number
                    style="width: 80px; text-align: center; border-left: 0"
                    :min="0"
                    :step="0.001"
                    :formatter="BaseTool.Amount.formatter"
                    :parser="BaseTool.Amount.parser"
                    v-model="projectQuantityEliminate"
                    placeholder="未工作"
                  />
                </a-form-item>
                <a-form-item>
                  <a-input
                    style=" width: 50px; border-left: 0; pointer-events: none; backgroundColor: #fff"
                    v-model="projectQuantitySiteUnit"
                    disabled
                  />
                </a-form-item>
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-tabs v-if="sbInfos.length>0" v-model="activeKey" hide-add type="editable-card" @edit="onEdit">
      <a-tab-pane :force-render="true" v-for="pane in sbInfos" :key="pane.sbId" :tab="pane.sbName" :closable="pane.closable">
        <fill-form :sb-info="pane" :ref="pane.sbId" :project-quantity-list="projectQuantityList" :fill-info-list="pane.fillInfoList" />
      </a-tab-pane>
    </a-tabs>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <sb-info-select-modal-by-user :type="'checkbox'" ref="sbInfoSelectModalByUser" @selected="handleSbSelected"/>
  </a-modal>
</template>

<script>
import SbInfoSelectModalByUser from '@/views/sb/info/modules/SbInfoSelectModalByFilter'
import FillForm from '@/views/sb/run-fill/modules/FillForm'
import { addSbRunFills } from '@/api/sb/run-fill'
import { addSbInspectionFill } from '@/api/sb/inspection-fill'
import { queryFillExecuteBySbIdUseType } from '@/api/fill/execute'
import { getFillProjectQuantityTree } from '@/api/fill/project-quantity'

export default {
  name: 'BaseSbRunFillList',
  components: {
    SbInfoSelectModalByUser,
    FillForm
  },
  props: {
    fillFilter: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      activeKey: null,
      sbInfos: [
      ],
      useType: null,
      newTabIndex: 0,
      addSbConfirmLoading: false,
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      projectQuantityList: [],
      visible: false,
      projectQuantityId: null,
      projectQuantityStart: null,
      projectQuantityEnd: null,
      projectQuantityEliminate: null,
      projectQuantityItem: {},
      projectQuantityUnitMap: {},
      projectQuantitySiteUnit: '无'
      // 下拉框map
    }
  },
  created () {
    this.projectQuantityUnitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.FILL_PROJECT_QUANTITY_UNIT)
    getFillProjectQuantityTree({ filter: 1 }).then(res => {
      this.projectQuantityList = res.data
    })
  },
  methods: {
    base (record, useType) {
      this.visible = true
      this.useType = useType
      this.projectQuantityId = null
      this.projectQuantityStart = null
      this.projectQuantityEnd = null
      this.projectQuantityEliminate = null
      this.projectQuantitySiteUnit = '无'

      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '编辑'
    },
    callback (key) {
      console.log(key)
    },
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    add () {
      let sbFilter = 1
      if (this.fillFilter === 1) {
        // 我的设备列表
        sbFilter = 1
      } else if (this.fillFilter === 2) {
        // 主管的设备列表
        sbFilter = 2
      }
      this.$refs.sbInfoSelectModalByUser.base({ filter: sbFilter })
    },
    remove (targetKey1) {
      let activeKey = this.activeKey
      let lastIndex
      this.sbInfos.forEach((pane, i) => {
        if (pane.sbId === targetKey1) {
          lastIndex = i - 1
        }
      })
      const sbInfos = this.sbInfos.filter(pane => pane.sbId !== targetKey1)
      if (sbInfos.length && activeKey === targetKey1) {
        if (lastIndex >= 0) {
          activeKey = sbInfos[lastIndex].sbId
        } else {
          activeKey = sbInfos[0].sbId
        }
      }
      this.sbInfos = sbInfos
      this.activeKey = activeKey
    },
    fillInfoSaveValue (sbInfo, values) {
      const fillInfoList = sbInfo.fillInfoList
      const fillInfoMap = {}
      sbInfo.fillDate = values.fillDate.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      fillInfoList.forEach(item => {
        fillInfoMap[item.infoId] = item
      })
      Object.keys(values).forEach(infoId => {
        const startIndex = infoId.indexOf('Start')
        const endIndex = infoId.indexOf('End')
        const eliminateIndex = infoId.indexOf('Eliminate')
        const projectStartIndex = infoId.indexOf('ProjectQuantityS')
        const projectEndIndex = infoId.indexOf('ProjectQuantityE')
        const projectEliminateIndex = infoId.indexOf('ProjectQuantityT')
        const projectResultNumberIndex = infoId.indexOf('ProjectQuantityV')
        const remarkProjectQuantityIndex = infoId.indexOf('RemarkProjectQuantity')

        const startTimeIndex = infoId.indexOf('TimeS')
        const endTimeIndex = infoId.indexOf('TimeE')
        const eliminateTimeIndex = infoId.indexOf('TimeR')

        if (startIndex > 0) {
          const realInfoId = infoId.substring(0, startIndex)
          fillInfoMap[realInfoId].resultStart = values[infoId]
        } else if (endIndex > 0) {
          const realInfoId = infoId.substring(0, endIndex)
          fillInfoMap[realInfoId].resultEnd = values[infoId]
        } else if (eliminateIndex > 0) {
          const realInfoId = infoId.substring(0, eliminateIndex)
          fillInfoMap[realInfoId].resultEliminate = values[infoId]
        } else if (startTimeIndex > 0) {
          const realInfoId = infoId.substring(0, startTimeIndex)
          fillInfoMap[realInfoId].startTime = values[infoId].format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        } else if (endTimeIndex > 0) {
          const realInfoId = infoId.substring(0, endTimeIndex)
          fillInfoMap[realInfoId].endTime = values[infoId].format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        } else if (eliminateTimeIndex > 0) {
          const realInfoId = infoId.substring(0, eliminateTimeIndex)
          fillInfoMap[realInfoId].resultEliminate = values[infoId]
        } else if (projectStartIndex > 0) {
          const realInfoId = infoId.substring(0, projectStartIndex)
          fillInfoMap[realInfoId].resultStart = values[infoId]
        } else if (projectEndIndex > 0) {
          const realInfoId = infoId.substring(0, projectEndIndex)
          fillInfoMap[realInfoId].resultEnd = values[infoId]
        } else if (projectEliminateIndex > 0) {
          const realInfoId = infoId.substring(0, projectEliminateIndex)
          fillInfoMap[realInfoId].resultEliminate = values[infoId]
        } else if (projectResultNumberIndex > 0) {
          const realInfoId = infoId.substring(0, projectResultNumberIndex)
          fillInfoMap[realInfoId].resultNumber = values[infoId]
        } else if (remarkProjectQuantityIndex > 0) {
          const realInfoId = infoId.substring(0, remarkProjectQuantityIndex)
          fillInfoMap[realInfoId].remark = values[infoId]
        } else {
          const fillInfo = fillInfoMap[infoId]
          if (fillInfo != null) {
            if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_INT) {
              fillInfoMap[infoId].resultValue = values[infoId]
            } else if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_DECIMAL) {
              fillInfoMap[infoId].resultNumber = values[infoId]
            } else if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_STRING) {
              fillInfoMap[infoId].resultDesc = values[infoId]
            } else if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_XIA_LA) {
              fillInfoMap[infoId].resultValue = values[infoId]
            } else if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_DAN_XUAN) {
              fillInfoMap[infoId].resultValue = values[infoId]
            } else if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_PROJECT_QUANTITY) {
              console.log(555555, values[infoId])
              fillInfoMap[infoId].resultDesc = values[infoId]
            } else {

            }
          }
        }
      })
      const resultInfoList = []
      Object.values(fillInfoMap).forEach(fillInfo => {
        resultInfoList.push(fillInfo)
      })
      return resultInfoList
    },
    projectValueChange () {
      const start = this.projectQuantityStart
      const end = this.projectQuantityEnd
      if (this.BaseTool.Object.isNotBlank(start) || this.BaseTool.Object.isNotBlank(end)) {
        this.sbInfos.forEach(sbInfo => {
          const fillInfoList = sbInfo.fillInfoList
          for (let i = 0; i < fillInfoList.length; i++) {
            const fillInfo = fillInfoList[i]
            if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_PROJECT_QUANTITY) {
              const setFieldsValue = this.$refs[sbInfo.sbId][0].form.setFieldsValue
              const v = {}
              if (this.BaseTool.Object.isNotBlank(start)) {
                v[fillInfo.infoId + 'ProjectQuantityS'] = start
              }
              if (this.BaseTool.Object.isNotBlank(end)) {
                v[fillInfo.infoId + 'ProjectQuantityE'] = end
              }
              setFieldsValue(v)
            }
          }
        })
      }
    },
    changeProjectQuantity () {
      if (this.projectQuantityId != null) {
        // 存入作业
        this.sbInfos.forEach(sbInfo => {
          const fillInfoList = sbInfo.fillInfoList
          for (let i = 0; i < fillInfoList.length; i++) {
            const fillInfo = fillInfoList[i]
            if (fillInfo.type === this.DictCache.VALUE.FILL_INFO_TYPE.FILL_INFO_TYPE_PROJECT_QUANTITY) {
              const setFieldsValue = this.$refs[sbInfo.sbId][0].form.setFieldsValue
              const v = {}
              v[fillInfo.infoId] = this.projectQuantityId
              v[fillInfo.infoId + 'Unit'] = this.projectQuantityUnitMap[this.projectQuantityItem.siteUnit]
              v[fillInfo.infoId + 'VUnit'] = this.projectQuantityUnitMap[this.projectQuantityItem.unit]
              setFieldsValue(v)
            }
          }
        })
      }
      this.projectValueChange()
    },
    projectQuantityChange (val, r, t) {
      if (!val) {
        return
      }
      const item = t.triggerNode.dataRef.item
      this.projectQuantityItem = item
      this.projectQuantitySiteUnit = this.projectQuantityUnitMap[item.siteUnit]
    },
    save () {
      const saveFillInfoList = []
      this.confirmLoading = true
      let isSuccess = true
      // 循环处理数据
      for (const sbInfo of this.sbInfos) {
        if (isSuccess) {
          const validateFieldsAndScroll = this.$refs[sbInfo.sbId][0].form.validateFieldsAndScroll
          validateFieldsAndScroll((errors, values) => {
            if (errors) {
              this.confirmLoading = false
              this.$message.error(sbInfo.sbName + '中有数据错误，提示信息：' + Object.values(errors)[0].errors[0].message)
              isSuccess = false
              return
            }
            sbInfo.fillInfoList = this.fillInfoSaveValue(sbInfo, values)
            saveFillInfoList.push(sbInfo)
          })
        }
      }
      if (isSuccess) {
        if (this.DictCache.VALUE.FILL_INFO_USE_TYPE.FILL_INFO_USE_TYPE_YUN_XING === this.useType) {
          addSbRunFills(saveFillInfoList)
            .then(() => {
              this.handleCancel(saveFillInfoList)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else if (this.DictCache.VALUE.FILL_INFO_USE_TYPE.FILL_INFO_USE_TYPE_XUN_JIAN === this.useType) {
          addSbInspectionFill(saveFillInfoList)
            .then(() => {
              this.handleCancel(saveFillInfoList)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base({})
    },
    handleSbSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      // 日期处理
      const sbInfos = this.sbInfos
      for (const sbInfo of sbInfos) {
        if (sbInfo.sbId === key) {
          this.$message.error('该设备已选择,请重新选择设备')
          return
        }
      }
      this.addSbConfirmLoading = true
      const promiseList = []
      const useType = this.useType
      rows.forEach((item, index, arr) => {
        const promise = new Promise((resolve, reject) => {
          queryFillExecuteBySbIdUseType({ sbId: item.id, useType: useType }).then(res => {
            const response = {}
            response.sbInfo = item
            response.sbInfo.fillDate = res.data.fillDate
            response.fillInfoList = res.data.fillInfoList
            resolve(response)
          }, err => {
            reject(null)
          })
        })
        promiseList.push(promise)
      })
      Promise.all(promiseList).then(res => {
        const activeKey = `${res[0].sbInfo.id}`
        res.forEach((item, index, arr) => {
          sbInfos.push({
            'sbId': item.sbInfo.id,
            'sbNo': item.sbInfo.no,
            'sbName': item.sbInfo.name,
            'fillDate': item.sbInfo.fillDate,
            'fillInfoList': item.fillInfoList
          })
        })
        console.log(11111, sbInfos)
        this.sbInfos = sbInfos
        this.activeKey = activeKey
      }).finally(res => {
        this.addSbConfirmLoading = false
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.sbInfos = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
