<template>
  <div>
    <!-- <p-card title="复核员业务关系">

     </p-card> -->
    <search-table
      ref="searchTable"
      :searchItems="searchItems"
      tableTitle="拣货人员安排表"
      tableRowKey="workId"
      :tableColumns="columns"
      :tableRemoteUrl="{ url: upcloud_base_wh_control + '/checkWorkGroup/page', method: 'get' }"
      :tableRemoteParams="remoteParams"
      :tableExtraBtns="tableEtraBtns"
      :tableOperators="tableOperators"
    >
    </search-table>

    <p-modal
      v-model="visible"
      :confirm-loading="confirmLoading"
      :title="detailItem ? '编辑' : '新增'"
      width="80%"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p-grid-form ref="form" :span="6" :items="formItems" />
      <p-button type="primary" @click="addworkingGroup">新增库区</p-button>
      <p-table-edit-pro
        ref="edittable"
        rowKey="workId"
        dragle
        editor-row-table
        :columns="EditTableColumns"
        :data-source.sync="EditTableData"
        :bordered="true"
      >
        <template slot="operation" slot-scope="text">
          <a @click="del(text)">删除</a>
        </template>
      </p-table-edit-pro>
    </p-modal>

    <p-modal
      v-model="visibleaddworkingGroup"
      title="新增库区"
      width="80%"
      @ok="addWorkGrouphandleOk"
      @cancel="visibleaddworkingGroup = false"
    >
      <p-grid-form ref="addform" :span="6" :items="AddWorkingGroupTable.items" @submit="hanlderSubmit" />
      <p-table
        ref="addtable"
        rowKey="warehouseAreaId"
        auto-width
        dragle
        editor-row-table
        :columns="AddWorkingGroupTable.columns"
        :data-source.sync="AddTableData"
        :remoteUrl="EditTableDataremoteUrl"
        :remoteBefore="remoteBefore2"
        :remoteParams="remoteParamsAddWorkingGroup"
        :bordered="true"
        :selected-row-keys.sync="EditTableDataSelectedRowKeys"
        @selectChange="addtableSelectChange"
      />
    </p-modal>
  </div>
</template>

<script>
import SearchTable from '../../components/search-table'
import { searchItems } from './config/searchItems'
import {
  formItems,
  tableCols1,
  tableCols2,
  EditTableColumns,
  EditTableDataremoteUrl,
  AddWorkingGroupTable
} from './config/modalConfig'
import { columns } from './config/columns'
import { addItem, updateItem, delItems, queryItemCategoryList, queryWorkstationList } from './api'
import { diffOption, forSelectText } from '@/views/kzyWMS/utils/index.js'
import { sorter } from '../../utils/sort'
import { upcloud_base_wh_control } from '@/config/serviceSettings'

export default {
  components: {
    'search-table': SearchTable
  },

  data() {
    return {
      AddWorkingGroupTable,
      EditTableDataremoteUrl,
      EditTableColumns,
      upcloud_base_wh_control,
      confirmLoading: false,
      searchItems: searchItems(this),
      columns: columns(this),
      remoteParams: { businesstype: '2011' },
      remoteParamsAddWorkingGroup: {},
      detailItem: null,
      tableEtraBtns: [
        {
          label: '新增',
          click: () => {
            this.showItem()
          }
        },
        {
          label: '批量删除',
          click: () => {
            this.deleteList()
          }
        }
      ],
      tableOperators: [
        {
          label: '修改',
          click: record => {
            this.showItem(record)
          }
        },
        {
          label: '删除',
          click: record => {
            this.deleteItem(record)
          }
        }
      ],
      // modal
      visible: false,
      visibleaddworkingGroup: false,
      formItems: formItems(this),
      tableCols1: tableCols1,
      tableCols2: tableCols2,
      tableData1: [],
      tableData2: [], // warehouseId=599581702716788736    isEnable=1
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      EditTableDataSelectedRowKeys: [],
      EditTableData: [],
      AddTableData: [],
      warehouseId: '',
      queryWarehouseId: '',
      addselectedRows: []
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) {
          this.warehouseId = ''
        }
      }
    }
  },

  created() {
    diffOption(columns(this)).then(res => {
      console.log(res)
      this.columns = sorter(res)
    })
    queryItemCategoryList().then(res => {
      if (!res.success) {
        this.$exception(res.message)
        return
      }
      this.tableData1 = res.data
    })
  },

  mounted() {
    this.$nextTick(() => {
      let warehouse = this.$store.state.user.warehouse
      this.$refs.searchTable.$refs.form.form.setFieldsValue(warehouse)
    })
  },

  methods: {
    //新增库区点击查询

    hanlderSubmit(event, form) {
      event.preventDefault()
      form.validateFields((err, value) => {
        if (!err) {
          console.log(value, '=========')
          this.remoteParamsAddWorkingGroup = { ...value }
        }
      })
    },
    //删除新增库区选中行
    del(text) {
      let that = this
      console.log(text)
      let key = text.workId
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        async onOk() {
          that.$refs.edittable.removeRow(key)
        },
        onCancel() {}
      })
    },
    //新增库区 选中
    addtableSelectChange(a, b) {
      this.addselectedRows = b
    },
    //新增库区点击确定
    addWorkGrouphandleOk() {
      console.log(this.addselectedRows)
      this.EditTableData = this.EditTableData.concat(this.addselectedRows)
      //   this.addselectedRows
      this.visibleaddworkingGroup = false
      this.EditTableDataSelectedRowKeys = []
    },
    // 新增库区
    addworkingGroup() {
      this.visibleaddworkingGroup = true
      this.$nextTick(() => {
        this.$refs.addform.form.resetFields()
        this.remoteParamsAddWorkingGroup = {}
        // console.log(this.remoteParamsAddWorkingGroup)
        this.remoteParamsAddWorkingGroup = { ...this.remoteParamsAddWorkingGroup }
      })
    },
    disableItem(record) {
      if (record) {
        this.$refs.form.form.enableItem(['workarea'])
        return
      }
      if (this.warehouseId) {
        this.$refs.form.form.enableItem(['workarea'])
      } else {
        this.$refs.form.form.disableItem(['workarea'])
      }
    },
    showItem(record) {
      console.log(record)
      this.detailItem = record || null
      this.visible = true
      this.$nextTick(() => {
        this.disableItem(record)
      })
      if (record) {
        console.log(record)
        this.$nextTick(() => {
          // let warehouse = this.$store.state.user.warehouse;
          this.$refs.form.form.disableItem(['workercode', 'warehouseName'])
          this.$refs.form.form.setFieldsValue({
            ...record,
            jobnumber: record.workercode,
            locname: record.personName
          })
          if (record.itemCategoryCodes) this.selectedRowKeys1 = record.itemCategoryCodes.split(',')
          if (record.stationIds) this.selectedRowKeys2 = record.stationIds.split(',')
          this.EditTableData = record.workgroupSubVOList
          this.getTableDataList()
        })
      } else {
        this.$nextTick(() => {
          this.$refs.form.form.enableItem(['workercode', 'warehouseName'])
          this.$refs.form.form.resetFields()
          this.EditTableData = []
        })
      }
    },
    remoteBefore(res, remoteParams) {
      // console.log(remoteParams, 'remoteParamsremoteParams')
      let warehouse = this.$store.state.user.warehouse
      remoteParams.params.warehouseId = this.queryWarehouseId || warehouse.warehouseId
      return remoteParams
    },
    remoteBefore2(res, remoteParams) {
      let warehouse = this.$store.state.user.warehouse
      remoteParams.params.warehouseId = this.warehouseId || warehouse.warehouseId
      return remoteParams
    },
    selectedChange(key, selectedRowKeys, selectedRows) {
      this.$refs.form.form.setFieldsValue({
        [key]: selectedRowKeys && selectedRowKeys.length > 0 ? selectedRowKeys.join(',') : null
      })
    },

    formWarehouseChange() {
      this.getTableDataList()
    },

    handleOk() {
      let that = this
      let data
      //   let workgroupSubVOList
      this.$refs.form.form.validateFields((err, value) => {
        if (err) {
          return
        }
        // console.log(data)
        data = value
        console.log(data)
      })

      this.$refs.edittable.validateFields(function(error, values, selectData) {
        if (error) {
          return
        } else {
          console.log(values)
          values.forEach((item, index) => {
            values[index] = { ...item, ...data }
          })
          data.workgroupSubVOList = values
          //   data = { ...data }
          console.log(data)
          that.confirmLoading = true
          if (that.detailItem) {
            that.handleUpdate({ ...data, workId: that.detailItem.workId })
          } else {
            that.handleAdd(data)
          }
          //
        }
      })
      console.log(data)
    },

    handleCancel() {
      this.detailItem = null
      this.selectedRowKeys1 = []
      this.selectedRowKeys2 = []
      this.visible = false
      this.EditTableData = []
    },

    deleteItem(item) {
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete([item.workId])
        }
      })
    },

    deleteList() {
      let list = this.$refs.searchTable.getSelectedItem()
      if (list.length == 0) {
        this.$message.error(this.$lang('请选择要删除的项'))
        return
      }
      let ids = []
      list.forEach(t => ids.push(t.workId))
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete(ids)
        }
      })
    },

    handleAdd(p) {
      return addItem(p).then(res => {
        this.confirmLoading = false
        if (!res.success) {
          this.$exception(res.message)
          return
        }
        this.$refs.searchTable.reload()
        this.$message.success(this.$lang('新增成功'))
        this.handleCancel()
      })
    },

    handleUpdate(p) {
      return updateItem(p).then(res => {
        this.confirmLoading = false
        if (!res.success) {
          this.$exception(res)
          return
        }

        this.$refs.searchTable.reload()
        this.$message.success(this.$lang('修改成功'))
        this.handleCancel()
      })
    },

    handleDelete(ids) {
      return delItems(ids).then(res => {
        if (!res.success) {
          this.$exception(res.message)
          return
        }
        this.$refs.searchTable.reload()
        this.$message.success(this.$lang('删除成功'))
      })
    },

    getTableDataList() {
      let vals = this.$refs.form.form.getFieldsValue()
      queryWorkstationList({ warehouseId: vals.warehouseId, isEnable: 1 }).then(res => {
        if (!res.success) {
          this.$exception(res.message)
          return
        }
        this.tableData2 = res.data
      })
    }
  }
}
</script>

<style></style>
