<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="['repairId']" />
      </a-form-item>
      <a-form-item
        label="维修单号"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['repairNo']" />
      </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-tree-select
          style="width: 100%"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          :treeData="spareTypeTreeData"
          :treeNodeFilterProp="'title'"
          @change="typeChange"
          :showSearch="true"
          v-decorator="['typeId', {rules: [{required: true, message: '类别不能为空'}]}]"
          placeholder="请选择"
        >
        </a-tree-select>
      </a-form-item>-->
      <a-form-item
        v-if="false"
        label="工程项目"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select
          v-decorator="['projectQuantityId',{rules: [{required: true, message: '作业名称不能为空'}]}]"
          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-form-item
        label="领用用途"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['reason', {rules: [{required: true, message: '用途不能为空'}]}]" placeholder="请选择">
          <a-select-option value="施工领用">
            施工领用
          </a-select-option>
          <a-select-option value="办公领用">
            办公领用
          </a-select-option>
          <a-select-option value="维修领用">
            维修领用
          </a-select-option>
          <a-select-option value="其他领用">
            其他领用
          </a-select-option>
        </a-select>
      </a-form-item>
      <!-- <a-form-item
          label="领用人"
          :labelCol="BaseTool.Constant.labelCol"
          :wrapperCol="BaseTool.Constant.wrapperCol"
      >
          <a-input disabled v-decorator="['pickUserName']" />
      </a-form-item>-->

      <!--<a-form-item
        label="状态"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select v-decorator="['status', {initialValue:DictCache.VALUE.SPARE_PICK_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"
          placeholder="请输入详细说明，或者施工内容"
          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>
               <a-divider type="vertical" />
              <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelOne(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </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/sparepickform'
import RepairFormSelectModal from '@/views/repair/form/modules/RepairFormSelectModal'
import DetailBaseForm from './DetailBaseForm'
import { queryUser } from '@/api/upms/user'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import { fetchSpareTypeTree } from '@/api/sqarepartmanage/sparetype'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModal'
import { queryFillProjectQuantityDeptProject } from '@/api/fill/project-quantity'

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

        {
          title: '备件名称',
          dataIndex: 'spareId',
          customRender: (text, record, index) => {
            return record.spareName
          }
        },
        {
          title: '编号',
          dataIndex: 'no'
        },
        {
          title: '备件规格',
          dataIndex: 'ggxh'
        },
        {
          title: '原厂编号',
          dataIndex: 'initNo'
        },
        {
          title: '库存价格',
          dataIndex: 'price'
        },
        {
          title: '库存数量',
          dataIndex: 'storeNum'
        },
        {
          title: '领用数量',
          dataIndex: 'num',
          customRender: (text, record, index) => {
            console.log(4444, text, record)
            return text
          }
        },
        {
          title: '总价',
          dataIndex: 'totalPrice',
          customRender: (text, record, index) => {
            console.log(3333, text, record)
            return text
          }
        },
        {
          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,
    SpareStoreSelectModal,
    StoreSelectModal
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_USE_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SPARE_PICK_FORM_STATUS)
    this.getUsers()
    // 下拉框map
    queryFillProjectQuantityDeptProject().then(res => {
      this.projectQuantityList = res.data
    })
  },
  methods: {
    getUsers () {
      queryUser({ status: 1 }).then(res => {
        this.userList = res.data
      })
    },
    base (record, param) {
      this.visible = true
      const { form: { setFieldsValue } } = this
      fetchSpareTypeTree({}).then(res => {
        this.spareTypeTreeData = res.data
      })
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        if (!this.BaseTool.Object.isBlank(param)) {
          this.$nextTick(() => {
            setFieldsValue(Object.assign(pick(param, [
              'repairId',
              'repairNo',
              'reason'
            ])))
          })
        }
        return
      }

      this.modalTitle = '编辑'
      this.storeId = record.storeId
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'pickNo',
          'storeId',
          'storeName',
          'totalPrice',
          'projectQuantityId',
          'reason',
          'remark',
          'status'
        ])))
      })
      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
            })
        }
      })
    },
    handleStoreSelect () {
      this.$refs.storeSelectModal.base({}, {})
    },
    handleStoreSelected (record, keys, rows) {
      // 重新选择了仓库，则明细需要全部清空
      this.data = []
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.storeId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'storeId': key,
          'storeName': row.name
        }))
      })
    },
    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,
          'repairNo': row.no
        }))
      })
    },
    typeChange (value) {
      this.typeId = value
    },
    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
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    },
    handleDelOne (id) {
      const data = [...this.data]
      this.data = data.filter(item => id !== item.id)
    },
    handleSpareSelect () {
      if (this.storeId == null) {
        this.$message.error('请先选择仓库')
        return
      }
      this.$refs.spareSelectModal.base({}, { storeId: this.storeId, num: 0 })
    },
    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 = 1.00
          row.storeId = this.storeId
          row.storeNum = row.num
          row.num = 1.00
          data.push(row)
        }
      }
    },
    handleEdit (record) {
      console.log(record.id)
      var key = record.id
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    }
  }
}
</script>
