<template>
  <a-card :bordered="false" v-show="visible" class="card" :title="modalTitle">
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['storeId']" type="hidden"/>
      </a-form-item>
      <a-row :gutter="24">
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="样品信息"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['param1', {rules: [{required: false, message: '入库单号不能为空'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="检测编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['param2']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="选择车间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['param3']" placeholder="请选择">
              <a-select-option value="一号车间">
                一号车间
              </a-select-option>
              <a-select-option value="二号车间">
                二号车间
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="水分/ppm"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['param4']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="固含量"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['param5', {rules: [{required: true, message: '不能为空'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="送样时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
              v-decorator="['param6']" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="检测时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
              v-decorator="['param7']" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row :gutter="48">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right;margin-top: 10px">
          <a-button type="primary" @click="save()">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addInStoreForm, updateInStoreForm } from '@/api/store/instoreform'
import DetailBaseForm from './DetailBaseForm'
import PurchaseOrderSelectModal from '@/views/purchase/purchase-order/modules/PurchaseOrderSelectModal'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import SparePartInfoSelectModal from '@/views/sqarepartmanage/sparepartinfo/modules/SparePartInfoSelectModal'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModal'
import { queryUsersByParentDeptNatureAll } from '@/api/upms/user'
import BaseTool from '@/utils/tool'

export default {
  name: 'BaseInStoreForm',
  components: {
    DetailBaseForm,
    StoreSelectModal,
    SparePartInfoSelectModal,
    PurchaseOrderSelectModal,
    SpareStoreSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      maskClosable: false,
      storeId: null,
      typeMap: {},
      userList: {},
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      // 表头
      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: 'num',
          width: 120,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '单价',
          dataIndex: 'price',
          width: 150,
          scopedSlots: { customRender: 'price' }
        },
        {
          title: '总价',
          dataIndex: 'totalPrice',
          width: 150,
          scopedSlots: { customRender: 'totalPrice' }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      user: this.$store.getters.userInfo,
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      }
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.IN_STORE_FORM_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      const params = { includeMy: true, deptId: this.user.companyId }
      params.nature = this.DictCache.VALUE.SYS_DEPT_NATURE.FEN_GONG_SI
      queryUsersByParentDeptNatureAll(params).then(res => {
        this.userList = res.data
      })
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      this.storeId = record.storeId
      record.userTime = this.BaseTool.Moment(record.userTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)

      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'inNo',
          'storeId',
          'userId',
          'userTime',
          'storeName',
          'purchaseId',
          'purchaseDispatchOrderId',
          'type',
          'remark'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.param6 = this.BaseTool.Date.formatter(values.param6, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        values.param7 = this.BaseTool.Date.formatter(values.param7, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        this.$message.info('更新成功')
        this.confirmLoading = false
        localStorage.setItem('test', JSON.stringify(values))
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      } else {
        this.$emit('ok')
      }
    },
    handleStoreSelect () {
      this.$refs.storeSelectModal.base({}, { filter: -1 })
    },
    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
        }))
      })
    },
    handlePurchaseOrderSelect () {
      this.$refs.purchaseOrderSelectModal.base({}, { filter: 0 })
    },
    handlePurchaseOrderSelected (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
        }))
      })
    },
    handleDetailSelect (record) {
      this.$refs.detailBaseForm.base(record)
    },
    handleDetailSelected (values) {
      const newData = [...this.data]
      for (let j = 0; j < newData.length; j++) {
        if (values.id === newData[j].id) {
          newData[j].num = values.num
          newData[j].price = values.price
          newData[j].totalPrice = values.totalPrice
          break
        }
      }
      this.data = newData
    },
    handleDel (id) {
      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)
    },
    handleSpareStoreSelect () {
      if (this.storeId == null) {
        this.$message.error('请先选择入库仓库')
        return
      }
      this.$refs.spareStoreSelectModal.base({}, { storeId: this.storeId })
    },
    handleSpareStoreSelected (record, keys, rows) {
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        var find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].spareId === data[j].spareId) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = rows[i]
          selectData.num = 1
          selectData.totalPrice = selectData.price
          data.push(selectData)
        }
      }
    },
    handleSpareSelect () {
      this.$refs.spareSelectModal.base()
    },
    handleSpareSelected (record, keys, rows) {
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        var find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].spareId === data[j].spareId) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = rows[i]
          selectData.num = 1
          selectData.spareId = rows[i].id
          selectData.spareName = rows[i].name
          selectData.price = rows[i].initialValue
          selectData.totalPrice = selectData.price
          data.push(selectData)
        }
      }
    },
    onQuantityChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      if (target) {
        target[attr] = value
        target['totalPrice'] = Math.floor(value * target['price'] * 10000) / 10000
        this.data = data
      }
    },
    onPriceChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      if (target) {
        target[attr] = value
        target['totalPrice'] = Math.floor(value * target['num'] * 10000) / 10000
        this.data = data
      }
    },
    onTotalPriceChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      if (target) {
        target[attr] = value
        target['price'] = Math.floor(value * 10000 / target['num']) / 10000
        this.data = data
      }
    }

  }
}
</script>
