<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"
             :title="detailItem?'编辑':'新增'"
             width="80%"
             @ok="handleOk"
             @cancel="handleCancel">

      <p-grid-form ref="form"
                   :span="6"
                   :items="formItems" />
    </p-modal>
  </div>
</template>

<script>
import SearchTable from "../../components/search-table";
import { searchItems } from "./config/searchItems";
import { formItems, tableCols1, tableCols2 } 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 { upcloud_base_wh_control } from "@/config/serviceSettings";

export default {

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

  data() {
    return {
      upcloud_base_wh_control,
      searchItems: searchItems(this),
      columns: columns(this),
      remoteParams: {businesstype: '2010'},//补货
      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,
      formItems: formItems(this),
      tableCols1: tableCols1,
      tableCols2: tableCols2,
      tableData1: [],
      tableData2: [], // warehouseId=599581702716788736    isEnable=1
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      warehouseId: '',
      queryWarehouseId: '',
    }
  },
  watch: {
    visible: {
      handler(val) {
        if(!val) {
          this.warehouseId = ''
        }
      }
    }
  },

  created() {
    diffOption(columns(this)).then(res => {
      console.log(res)
      this.columns = 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: {

    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) {
      this.detailItem = record || null;
      this.visible = true;
      this.$nextTick(() => {
        this.disableItem(record)
      });
      if (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.getTableDataList();
        });
      } else {
        this.$nextTick(() => {
          this.$refs.form.form.enableItem(['workercode', 'warehouseName'])
          this.$refs.form.form.resetFields()
        });
      }
    },
    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) {
      remoteParams.params.warehouseId = this.warehouseId
      return remoteParams
    },
    selectedChange(key, selectedRowKeys, selectedRows) {
      this.$refs.form.form.setFieldsValue({
        [key]: selectedRowKeys && selectedRowKeys.length > 0 ? selectedRowKeys.join(',') : null
      });
    },

    formWarehouseChange() {
      this.getTableDataList();
    },

    handleOk() {
      this.$refs.form.form.validateFields((err, value) => {
        if (err) {
          return;
        }
        // if (!value.itemCategoryCodes) {
        //   this.$message.warning('请选择商品大类');
        //   return;
        // }
        // if (!value.stationIds) {
        //   this.$message.warning('请选择复核台');
        //   return;
        // }
        if (this.detailItem) {
          this.handleUpdate({ ...value, workId: this.detailItem.workId });
        } else {
          this.handleAdd(value);
        }
      });
      // this.$emit('input', false);
    },

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

    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 => {
        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 => {
        if (!res.success) {
          this.$exception(res.message);
          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() {
      this.$nextTick(() => {
        console.log(this.$refs)
      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>