import _get from 'lodash.get'
import { post, get } from '@/utils/http'

export default {
  watch: {
    'form.dxStHouseInCome.id': {
      immediate: true,
      handler(id) {
        // 清空列表中目标库位等信息
        this.clearTargetInfo()
        if (id) {
          this.getDxStAreaOptions(id)
        }
      }
    }
  },
  computed: {
    // 表单上的目标库房id
    targetHouseId() {
      return _get(this.form, 'dxStHouseInCome.id', null)
    },
    indexRow() {
      return {
        title: '序号',
        align: 'center',
        width: '70'
      }
    },
    tableColums() {
      const baseColumns = [
        { title: '操作', key: 'operate', align: 'center', width: '100',
          component: {
            show: true,
            name: 'EditTableRow',
            props: {
              btns: [
                {
                  operation: '查看详情',
                  icon: '/icons/c-scan.png',
                  handleClick: (row, index) => {
                    const rowData = { ...row }
                    if (!rowData.id) {
                      rowData.id = '这个id只是为了DeeAsForm组件做自定义查询时候的判断使用'
                    }
                    this.rowData = rowData
                    this.showWlInfoDrawer = true
                  }
                }
              ]
            }
          }
        }
      ]
      if (!this.readonly) {
        baseColumns[0].component.props.btns.unshift({
          operation: '删除',
          icon: '/icons/c-creatbackups.png',
          handleClick: (row, index) => {
            this.dataSource = this.dataSource.filter((m, i) => i !== index)
            this.form.dxStMoveSendOutAFDs = this.dataSource
          }
        })
      }
      baseColumns.push(...[
        {
          title: '物料编号', key: 'instantiableResource.resourceNo', align: 'center'
        },
        {
          title: '物料名称', key: 'instantiableResource.name', align: 'center'
        },
        {
          title: '物料批次', key: 'batchNumber', align: 'center'
        },
        {
          title: '原库区', key: 'dxStAreaName', align: 'center'
        },
        {
          title: '原库位', key: 'dxStLocation.serialNumber', align: 'center'
        },
        {
          title: '库存数量', key: 'stockQuantity', align: 'center'
        },
        {
          title: '目标库区', key: 'dxStMoveInComeAFDs[0].dxStArea.id', align: 'center',
          component: this.readonly ? {
            show: true,
            render: (h, row, col, index) => {
              return <span>{ row.dxStMoveInComeAFDs[0].dxStArea.name }</span>
            }
          } : {
            name: 'tableCellFormCheck',
            show: true,
            props: {
              isRequire: true,
              formRules: [
                { required: true, message: '请输入', trigger: 'blur' }
              ],
              bindKey: 'dxStMoveInComeAFDs[0].dxStArea.id',
              component: {
                name: 'el-select-rowOptions',
                bindOptions: 'row.dxStMoveInComeAFDs[0].dxStAreaOptions',
                bindModelValue: 'row.dxStMoveInComeAFDs[0].dxStArea.id'
              }
            },
            handler: {
              changeForm: (valObj) => {
                const { row, index, val } = valObj
                const dxStAreaOptions = row.dxStMoveInComeAFDs[0].dxStAreaOptions || []
                const findItem = dxStAreaOptions.find(r => r.value === val)
                if (findItem) {
                  this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'dxStArea', findItem.data)
                  this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'dxStAreaName', findItem && findItem.data && findItem.data.name)
                  this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'dxStLocation', {})
                  this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'stockQuantity', null)
                  this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'inComeQuantity', null)
                  this.getDxStLocationOptions(this.dataSource[index], index)
                }
              }
            }
          }
        },
        {
          title: '目标库位', key: 'dxStMoveInComeAFDs[0].dxStLocation.id', align: 'center',
          component: this.readonly ? {
            show: true,
            render: (h, row, col, index) => {
              return <span>{ row.dxStMoveInComeAFDs[0].dxStLocation.serialNumber }</span>
            }
          } : {
            name: 'tableCellFormCheck',
            show: true,
            props: {
              isRequire: true,
              formRules: [
                { required: true, message: '请输入', trigger: 'blur' }
              ],
              bindKey: 'dxStMoveInComeAFDs[0].dxStLocation.id',
              component: {
                name: 'el-select-rowOptions',
                bindOptions: 'row.dxStMoveInComeAFDs[0].dxStLocationOptions',
                bindModelValue: 'row.dxStMoveInComeAFDs[0].dxStLocation.id'
              }
            },
            handler: {
              changeForm: (valObj) => {
                const { row, index, val } = valObj
                const dxStLocationOptions = row.dxStMoveInComeAFDs[0].dxStLocationOptions || []
                const findItem = dxStLocationOptions.find(r => r.value === val)
                this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'dxStLocation', findItem && findItem.data)
                this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'dxStLocationName', findItem && findItem.data && findItem.data.serialNumber)
                this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'stockQuantity', null)
                this.$set(this.dataSource[index].dxStMoveInComeAFDs[0], 'inComeQuantity', 1)
                // 表格中没有可存数量
                // this.getStockQuantity(row, index)
              }
            }
          }
        }
      ])
      // 不要此列
      // if (!this.readonly) {
      //   baseColumns.push({
      //     title: '可存数量', key: 'dxStMoveInComeAFDs[0].stockQuantity', align: 'center'
      //   })
      // }
      baseColumns.push({
        title: '申请数量', key: 'dxStMoveInComeAFDs[0].inComeQuantity', align: 'center',
        component: {
          show: true,
          render: (h, row, col, index) => {
            if (this.readonly) {
              return <span>{ row.dxStMoveInComeAFDs[0].inComeQuantity }</span>
            }
            return <el-input-number
              min={1}
              max={row.stockQuantity || 0}
              precision={2}
              v-model={row.dxStMoveInComeAFDs[0].inComeQuantity}
              v-on:change={(val) => {
                row.dxStMoveInComeAFDs[0].recordQuantity = val
                row.sendOutQuantity = val
                row.recordQuantity = val
                this.setRowValue(row, index)
              }}/>
          }
        }
      })
      return baseColumns
    }
  },
  methods: {
    // 清空目标信息
    clearTargetInfo() {
      this.dataSource.forEach(row => {
        this.$set(row.dxStMoveInComeAFDs, 0, {
          dxStArea: {
            id: null
          },
          dxStLocation: {
            id: null
          },
          stockQuantity: null,
          inComeQuantity: null,
          dxStAreaOptions: [],
          dxStLocationOptions: []
        })
      })
    },
    /**
     * 查询目标库区
     * @param {*} targetHouseId 目标库房id
     * @param {*} newItems 新添加的申请单数据
     */
    getDxStAreaOptions(targetHouseId, newItems) {
      const dataSource = Array.isArray(newItems) ? newItems : this.dataSource
      const allFetch = dataSource.map(row => {
        return post(`DxStOrgArea/findAreaListWithHouseId?houseId=${targetHouseId}&dxResClassId=${row.resourceClasscifyId}`)
      })
      this.loading = true
      Promise.all(allFetch)
        .then(resAll => {
          resAll.forEach((res, i) => {
            this.$set(dataSource[i].dxStMoveInComeAFDs[0], 'dxStAreaOptions', (res.items || []).map(m => {
              return {
                label: m.name,
                value: m.id,
                data: m
              }
            }))
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 查询目标库位
    _getDxStLocationOptions(row, rowIdx) {
      const areaId = row.dxStMoveInComeAFDs[0].dxStArea.id
      this.loading = true
      post(`/DxStOrgLocation/getStLocationForInCome?areaId=${areaId}&dxResClassId=${row.resourceClasscifyId}`)
        .then(res => {
          this.$set(this.dataSource[rowIdx].dxStMoveInComeAFDs[0], 'dxStLocationOptions', (res.items || []).map(m => {
            return {
              label: m.serialNumber,
              value: m.id,
              data: m
            }
          }))
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDxStLocationOptions(row, rowIdx) {
      const areaId = row.dxStMoveInComeAFDs[0].dxStArea.id
      this.loading = true
      const params = {
        'searchItems': {
          'items': [
            {
              'fieldName': 'parentId',
              'operator': 'EQ',
              'value': areaId
            }
          ],
          'operator': 'AND'
        }
      }
      this.$api.searchApi('DxStOrgLocation', params)
        .then(res => {
          this.$set(this.dataSource[rowIdx].dxStMoveInComeAFDs[0], 'dxStLocationOptions', res.items.content.map(m => {
            return {
              label: m.serialNumber,
              value: m.id,
              data: m
            }
          }))
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 查询可存数量<废弃,现在模型没有库存数量>
    async getStockQuantity(row, rowIdx) {
      const locationId = row.dxStMoveInComeAFDs[0].dxStLocation.id
      this.loading = true
      get(`/DxStInventoryAccount/getStockQuantity?modelName=DxStLocation&locationId=${locationId}`)
        .then(res => {
          this.$set(this.dataSource[rowIdx].dxStMoveInComeAFDs[0], 'stockQuantity', res.items || 0)
        })
        .finally(() => {
          this.loading = false
        })
    },
    setRowValue(row, rowIdx) {
      this.dataSource[rowIdx] = row
    }
  }
}