<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <a-form-item
        label="退库单号"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['pickNo']" />
      </a-form-item>
      <a-form-item
         label="仓库id"
         :labelCol="BaseTool.Constant.labelCol"
         :wrapperCol="BaseTool.Constant.wrapperCol"
         v-show="false"
      >
         <a-input
           v-decorator="['storeId', {rules: [{required: true, message: '仓库id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
         label="仓库"
         :labelCol="BaseTool.Constant.labelCol"
         :wrapperCol="BaseTool.Constant.wrapperCol"
      >
         <a-input
           disabled
           style="width:70%;margin-right:5px"
           v-decorator="['storeName', {rules: [{required: true, message: '仓库名称不能为空'}]}]" />
         <a-button type="primary" @click="handleStoreSelect">选择仓库</a-button>
      </a-form-item>
      <a-form-item
        label="退库原因"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['type', {initialValue:DictCache.VALUE.SPARE_BACK_FORM_TYPE.QUESTION,rules: [{required: true, message: '退库类型不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in typeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!--<a-form-item
        label="退库人"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['pickUserId', {rules: [{required: true, message: '退库人不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.realName"
            :value="item.userId">{{ item.realName }}
          </a-select-option>
        </a-select>
      </a-form-item>-->

      <a-form-item
        label="退库说明"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          v-decorator="['reason', {rules: [{required: true, message: '退库说明不能为空'}]}]" />
      </a-form-item>
      <!--<a-form-item
        label="状态"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['status', {initialValue:DictCache.VALUE.SPARE_BACK_FORM_STATUS.APPROVAL_PENDING,rules: [{required: true, message: '状态不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in statusMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>-->
      <a-form-item
        label="备注"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-textarea
          :rows="4"
          v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
      </a-form-item>
    </a-form>
    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="退库详情">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleSpareSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :row-selection="rowSelection">
          <span slot="action" slot-scope="record">
            <template>
              <a @click="handleDetailSelect(record)">修改</a>
            </template>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <detail-base-form ref="detailBaseForm" @selected="handleDetailSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <repair-form-select-modal ref="repairSelectModal" @selected="handleRepairNoSelected"/>
    <store-select-modal ref="storeSelectModal" @selected="handleStoreSelected"/>
    <spare-store-select-modal ref="spareSelectModal" @selected="handleSpareSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addSparePickForm, updateSparePickForm } from '@/api/store/sparebackform'
import RepairFormSelectModal from '@/views/repair/form/modules/RepairFormSelectModal'
import DetailBaseForm from './DetailBaseForm'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModal'
import { queryUser } from '@/api/upms/user'

export default {
  name: 'BaseSpareBackForm',
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      storeId: null,
      // 下拉框map
      typeMap: {},
      statusMap: {},
      userList: [],
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '备件名称',
          dataIndex: 'spareId',
          customRender: (text, record, index) => {
            return record.spareName
          }
        },

        {
          title: '退库数量',
          dataIndex: 'num'
        },
        {
          title: '库存价格',
          dataIndex: 'price'
        },
        {
          title: '总价',
          dataIndex: 'totalPrice'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      }
    }
  },
  components: {
    RepairFormSelectModal,
    DetailBaseForm,
    StoreSelectModal,
    SpareStoreSelectModal,
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_BACK_FORM_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_BACK_FORM_STATUS)
    this.getUsers()
  },
  methods: {
    getUsers () {
      queryUser({ status: 1 }).then(res => {
        this.userList = res.data
      })
    },
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      this.storeId = record.storeId
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'storeId',
          'storeName',
          'pickNo',
          'type',
          'reason',
          'remark'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data.length === 0) {
          this.$message.error('请添加退库详情')
          this.confirmLoading = false
          return
        }
        values.detailList = this.data
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addSparePickForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSparePickForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    handleRepairNoSelect () {
      this.$refs.repairSelectModal.base()
    },
    handleRepairNoSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'repairId': key,
          'repaireNo': row.no
        }))
      })
    },
    handleSpareSelect () {
    if(this.storeId==null){
      this.$message.error("请先选择仓库")
      return
    }
    this.$refs.spareSelectModal.base({},{storeId:this.storeId})
  },
  handleSpareSelected (record, keys, rows) {
    const { data } = this
    const len = data.length
    for (let i = 0; i < rows.length; i++) {
      const row = rows[i]
      let flag = false
      for (let j = 0; j < len; j++) {
        if (row.spareId === data[j].spareId) {
          flag = true
        }
      }
      if (!flag) {
        row.totalPrice = row.price
        row.storeId = this.storeId
        row.price = row.price
        row.num = 1.00
        data.push(row)
      }
    }
  },
    handleDetailSelect (record) {
      this.$refs.detailBaseForm.base(record)
    },
    handleDetailSelected (record) {
      const { data } = this
      const myData = []
      const len = data.length
      for (let j = 0; j < len; j++) {
        if (record.spareId === data[j].spareId) {
          data[j].num = record.num
          data[j].totalPrice = record.totalPrice
        }
        myData.push(data[j])
      }
      this.data = myData
    },
    handleStoreSelect () {
      this.$refs.storeSelectModal.base({},{filter: 2})
    },
    handleStoreSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.storeId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'storeId': key,
          'storeName': row.name
        }))
      })
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    }

  }
}
</script>
