<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="4">
            <a-button type="primary" icon="plus" @click="add" :loading="addSbConfirmLoading">
              新增设备
            </a-button>
          </a-col>
          <a-col :span="8">
            <a-button
              style="margin-left: 8px"
              type="primary"
              @click="()=> this.$refs.storeSelectModal.base({},{},{filter: 2})">
              选择仓库
            </a-button>
            <span style="margin-left: 8px;">{{ store.name || '未选择' }}</span>
          </a-col>
          <a-col :span="6">
            <a-button
              style="margin-left: 8px"
              type="primary"
              @click="handleSpareSelect">
              选择燃油
            </a-button>
            <span style="margin-left: 8px;">{{ spareStore.spareName || '未选择' }}</span>
          </a-col>
          <a-col :span="6" v-show="false">
            <a-form-item label="工程项目">
              <a-select
                style="width: 150px;"
                @change="projectQuantityChange"
                v-model="projectQuantityId"
                placeholder="请选择">
                <a-select-option
                  v-for="(item,index) in projectQuantityList"
                  :key="index"
                  :label="item.name"
                  :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
            </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">
        <oil-add-form :project-quantity-list="projectQuantityList" :ref="pane.sbId" :oil-model="pane" />
      </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"/>
    <store-select-modal ref="storeSelectModal" @selected="handleStoreSelected"/>
    <spare-store-page-modal ref="spareStorePageModal" :type="'radio'" @selected="handleSpareStoreSelected"/>
  </a-modal>
</template>

<script>
import SbInfoSelectModalByUser from '@/views/sb/info/modules/SbInfoSelectModalByFilter'
import OilAddForm from '@/views/sb/oil/modules/OilAddForm'
import { fetchSbOilBySbId, addSbOilList } from '@/api/sb/oil'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import SpareStorePageModal from '@/views/store/sparestore/modules/SpareStorePageModal'
import { queryFillProjectQuantityDeptProject } from '@/api/fill/project-quantity'

export default {
  name: 'BaseSbRunFillList',
  components: {
    SbInfoSelectModalByUser,
    StoreSelectModal,
    OilAddForm,
    SpareStorePageModal
  },
  props: {
    oilFilter: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      activeKey: null,
      sbInfos: [
      ],
      store: {},
      spareStore: {},
      projectQuantityId: null,
      useType: null,
      newTabIndex: 0,
      addSbConfirmLoading: false,
      confirmLoading: false,
      projectQuantityList: [],
      modalTitle: null,
      visible: false
      // 下拉框map
    }
  },
  created () {
    // 下拉框map
    queryFillProjectQuantityDeptProject().then(res => {
      this.projectQuantityList = res.data
    })
  },
  methods: {
    base (record, useType) {
      this.visible = true
      this.modalTitle = '加油申请'
    },
    callback (key) {
      console.log(key)
    },
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    add () {
      let sbFilter = 1
      if (this.oilFilter === 1) {
        // 我的设备列表
        sbFilter = 1
      } else if (this.oilFilter === 2) {
        // 主管的设备列表
        sbFilter = 2
      }
      this.$refs.sbInfoSelectModalByUser.base({ filter: sbFilter })
    },
    handleSpareSelect () {
      if (this.BaseTool.Object.isBlank(this.store) || this.BaseTool.String.isBlank(this.store.id)) {
        this.$message.error('请先选择仓库')
        return
      }
      const storeId = this.store.id
      this.$refs.spareStorePageModal.base({}, { storeId: storeId, num: 0, typeNameLike: '燃油' })
    },
    handleStoreSelected (record, keys, rows) {
      const [ row ] = rows
      this.store = row
      this.spareStore = {}
      this.sbInfos.forEach(sbInfo => {
        const setFieldsValue = this.$refs[sbInfo.sbId][0].form.setFieldsValue
        setFieldsValue({
          'storeId': row.id,
          'storeName': row.name,
          'spareName': null,
          'spareStoreId': null
        })
      })
    },
    handleSpareStoreSelected (record, keys, rows) {
      const [ row ] = rows
      this.spareStore = row
      this.sbInfos.forEach(sbInfo => {
        const setFieldsValue = this.$refs[sbInfo.sbId][0].form.setFieldsValue
        setFieldsValue({
          'spareStoreId': row.id,
          'spareName': row.spareName
        })
      })
    },
    projectQuantityChange (val) {
      this.sbInfos.forEach(sbInfo => {
        const setFieldsValue = this.$refs[sbInfo.sbId][0].form.setFieldsValue
        setFieldsValue({
          'projectQuantityId': val
        })
      })
    },
    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
    },
    save () {
      this.confirmLoading = true
      const saveList = []
      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
            }
            saveList.push(values)
          })
        }
      }
      if (isSuccess) {
        addSbOilList(saveList).then(res => {
          this.handleCancel(saveList)
        }).catch(() => {
          this.confirmLoading = false
        })
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base({})
    },
    handleSbSelected (keys, rows) {
      const [ key ] = keys
      // 日期处理
      const sbInfos = this.sbInfos
      for (const sbInfo of sbInfos) {
        if (sbInfo.sbId === key) {
          this.$message.error('该设备已选择,请重新选择设备')
          return
        }
      }
      this.addSbConfirmLoading = true
      const promiseList = []
      rows.forEach((item, index, arr) => {
        const promise = new Promise((resolve, reject) => {
          fetchSbOilBySbId({ sbId: item.id }).then(res => {
            const response = {}
            response.sbInfo = item
            response.model = res.data
            resolve(response)
          }, () => {
            reject(new Error(null))
          })
        })
        promiseList.push(promise)
      })
      Promise.all(promiseList).then(res => {
        const activeKey = `${res[0].sbInfo.id}`
        res.forEach((item, index, arr) => {
          let s = {}
          if (this.BaseTool.Object.isNotBlank(item.model)) {
            s = item.model
          } else {
            s = {
              'sbId': item.sbInfo.id,
              'sbNo': item.sbInfo.no,
              'sbName': item.sbInfo.name,
              'sbCardNo': item.sbInfo.cardNo
            }
          }
          if (this.BaseTool.Object.isNotBlank(this.store) && this.BaseTool.String.isNotBlank(this.store.id)) {
            s.storeId = this.store.id
            s.storeName = this.store.name
          }
          if (this.BaseTool.Object.isNotBlank(this.spareStore) && this.BaseTool.String.isNotBlank(this.spareStore.id)) {
            s.spareStoreId = this.spareStore.id
            s.spareName = this.spareStore.spareName
          }
          if (this.BaseTool.String.isNotBlank(this.projectQuantityId)) {
            s.projectQuantityId = this.projectQuantityId
          }
          sbInfos.push(s)
        })
        this.sbInfos = sbInfos
        this.activeKey = activeKey
      }).finally(res => {
        this.addSbConfirmLoading = false
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.store = {}
      this.sbInfos = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
