<template>
  <div class="workstation">
    <a-row>
      <a-col :span="14">
        <p-card style="min-height:400px;">
          <template slot="title">
            <div class="card-custom-title">
              <div>工作站管理</div>
              <div>
                <p-button type="primary"
                          icon="plus"
                          @click="showModal(true)">新增</p-button>
                <p-button type="primary"
                          icon="download"
                          style="margin-left: 10px">导出</p-button>
              </div>
            </div>
          </template>

          <div class="plg-inner-form-mb">
            <p-grid-form ref="search"
                         :span="8"
                         :label-col="{ span: 8 }"
                         :items="items"
                         @submit="hanlderSubmit"></p-grid-form>
          </div>

          <p-table ref="maintable"
                   :has-row-count="true"
                   :autoLoad="false"
                   :columns="columns"
                   :data-source.sync="data"
                   :remoteUrl="{url: SERVICE_DATA_API_BASE+'/search/page', method: 'post'}"
                   :remoteBefore="remoteBefore"
                   :remoteData="remoteParams"
                   :remoteParams="remoteParams"
                   rowKey="stationId"
                   bordered
                   @clickRow="clickRow">
            <template slot="action"
                      slot-scope="text, record">
              <a @click="showModal(false, record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="您确定要删除吗?"
                            ok-text="确认"
                            cancel-text="取消"
                            @confirm="delSingle(record)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </p-table>
        </p-card>
      </a-col>
      <a-col :span="10"
             style="padding-left:10px;">
        <p-card :tab-list="tabList"
                :active-tab-key="noTitleKey"
                style="min-height:400px;"
                @tabChange="key => onTabChange(key)">
          <div slot="tabBarExtraContent">
            <a-button v-show="noTitleKey=='tab2' && clickRecord"
                      type="primary"
                      @click="showSlideModal(true)">新增</a-button>
          </div>
          <p-table v-show="noTitleKey === 'tab1'"
                   :rowKey="'warehouseAreaId'"
                   :columns="whAreaColumns"
                   :data-source.sync="whAreaData"
                   :selectedRowKeys.sync="whAreaSelectedRowKeys"
                   bordered
                   :loading="whAreaLoading"
                   @selectChange="whAreaChange" />
          <div v-show="noTitleKey === 'tab2'">
            <p-table ref="stationTable"
                     :rowKey="'stationId'"
                     :autoLoad="false"
                     :colorTransformRow="false"
                     :rowSelectType="false"
                     :remoteUrl="{url: upcloud_base_wh+'/wmsWhSlideway/v1/findAll'}"
                     :remoteData="whSlideRemoteParams"
                     :remoteParams="whSlideRemoteParams"
                     :columns="whSlideColumns"
                     :data-source.sync="whSlideData"
                     :loading="whAreaLoading"
                     bordered>
              <template slot="action"
                        slot-scope="text, record">
                <a @click="showSlideModal(false, record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm title="您确定要删除吗?"
                              ok-text="确认"
                              cancel-text="取消"
                              @confirm="delSlide(record)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </p-table>
          </div>
        </p-card>
      </a-col>
    </a-row>

    <p-modal :title="actionType ? '工作站新增' : '工作站修改'"
             :visible="visible"
             :confirm-loading="confirmLoading"
             @ok="handleOk"
             @cancel="handleCancel"
             :maskClosable="false"
             :enlargeable="true"
             :draggable="true"
             width="80%">
      <p-grid-form ref="modelForm"
                   :span="8"
                   :label-col="{ span: 9 }"
                   :items="modalItems"></p-grid-form>
    </p-modal>

    <p-modal :title="whSlideActionType ? '滑道新增' : '滑道修改'"
             :visible="whSlideVisible"
             @ok="handleSlideOk"
             @cancel="handleSlideCancel"
             :maskClosable="false">
      <p-grid-form ref="slideForm"
                   :span="24"
                   :label-col="{ span: 9 }"
                   :items="whSlideItems"></p-grid-form>
    </p-modal>

  </div>
</template>

<script>
import { items, modalItems, columns, whAreaColumns, whSlideColumns, whSlideItems } from './config/workstation'
import {
  workstationAdd, workstationDelete, workstationUpdate,
  workstationWhArea, workstationWhAreaAdd, workstationWhAreaDel,
  workstationSlide, workstationSlideAdd, workstationSlideUpload, workstationSlideDel
} from './api/api.js'
import { baseWmsWarehouseArea_findAll } from "./api/api_warehouse";
import { setwarehouse } from './config/warehousemixin.js'
import { sorter } from '../../utils/sort'
import { upcloud_base_wh ,SERVICE_DATA_API_BASE} from "@/config/serviceSettings";

export default {
  name: 'Workstation',
  mixins: [setwarehouse],
  data() {
    return {
      upcloud_base_wh :upcloud_base_wh ,
      SERVICE_DATA_API_BASE:SERVICE_DATA_API_BASE,
      items,
      modalItems: modalItems(this),
      data: [],
      columns:null,
      remoteParams: {},
      visible: false,
      confirmLoading: false,
      actionType: true,
      record: {},
      tabList: [{ key: 'tab1', tab: '库区' }, { key: 'tab2', tab: '滑道' }],
      noTitleKey: 'tab1',
      clickRecord: null,
      whAreaLoading: false,
      whAreaColumns, whAreaData: [], whAreaList: [], whAreaSelectedRowKeys: [],
      whSlideColumns, whSlideData: [], whSlideList: [], whSlideSelectedRowKeys: [],
      whSlideItems, whSlideVisible: false, whSlideActionType: true, whSlideRecord: null,
      whSlideRemoteParams: {},
    }
  },

  created() {
    this.columns = sorter(columns)
  },
  methods: {

    remoteBefore(vn, params) {
      let p = { ...params }
      let pp = { ...params.data };
      delete pp.pageNum;
      delete pp.pageSize;
      p.data = {
        num: '579666970018975744',
        pageNum: params.data.pageNum, pageSize: params.data.pageSize,
        params: pp
      };
      return p; 
    },

    hanlderSubmit(event, form) {
      event.preventDefault()
      form.validateFields((err, values) => {
        if (!err) {
          this.remoteParams = values
        }
      })
    },

    showModal(bool, record) {
      this.visible = true
      this.actionType = bool

      this.$nextTick(() => {
        const { form } = this.$refs.modelForm
        if (bool) {
          form.resetFields()
        } else {
          this.record = record
          record.isEnable = record.isEnable == 1 ? true : false
          form.setFieldsValue(record)
        }
      })
    },

    delSingle(record) {
      workstationDelete({ ids: record.stationId }).then(res => {
        if (res.success) {
          this.visible = false
          this.$message.success('操作成功')
          this.$refs.maintable.reload();
        } else {
          this.$exception(res)
        }
      })
    },

    handleOk(e) {
      this.confirmLoading = true
      const { actionType, record } = this
      this.$refs.modelForm.form.validateFields(async (error, values) => {
        if (!error) {
          values.isEnable = values.isEnable ? 1 : 0
          values.abnormalFlag = values.abnormalFlag ? 1 : 0
          const res = actionType
            ? await workstationAdd(values)
            : await workstationUpdate({ ...values, stationId: record.stationId })
          let msg = res.message
          if (res.success) {
            this.visible = false
            this.$message.success(msg || '操作成功')
          } else {
            // this.$message.warning(msg || '操作失败')
            this.$exception(res)
          }
          this.$refs.maintable.reload();
        }
      })
      this.confirmLoading = false
    },

    handleCancel(e) {
      this.visible = false
    },

    clickRow(event, rowkey, record) {
      this.clickRecord = record;
      this.getWhAreaList();
      this.getWorkstationWhArea();
      this.whSlideRemoteParams = { stationId: record.stationId };
    },

    onTabChange(key) {
      this.noTitleKey = key;
    },

    getWhAreaList() {
      if (!this.clickRecord) return;
      baseWmsWarehouseArea_findAll({ warehouseId: this.clickRecord.warehouseId }).then(res => {
        if (!res.success) {
          this.$exception(res)
          return;
        }
        this.whAreaData = res.data;
      });
    },
    getWorkstationWhArea() {
      if (!this.clickRecord || this.whAreaLoading) return;
      this.whAreaLoading = true;
      workstationWhArea({ stationId: this.clickRecord.stationId }).then(res => {
        this.whAreaLoading = false;
        if (!res.success) {
          this.$exception(res)
          return;
        }
        this.whAreaList = res.data;
        setTimeout(() => {
          this.whAreaSelectedRowKeys = res.data.map(t => t.warehouseAreaId);
        }, 100);
      });
    },

    whAreaChange(indexList, recordList) {
      let addList = recordList.filter(t => !this.whAreaList.some(tt => tt.warehouseAreaId === t.warehouseAreaId))
        .map(t => ({ warehouseId: t.warehouseId, warehouseAreaId: t.warehouseAreaId, stationId: this.clickRecord.stationId }));
      let delList = this.whAreaList.filter(t => !recordList.some(tt => tt.warehouseAreaId === t.warehouseAreaId)).map(t => t.whAreaStationId);
      let arr = [];
      if (addList.length > 0) arr.push(workstationWhAreaAdd(addList));
      if (delList.length > 0) arr.push(workstationWhAreaDel(delList));
      Promise.all(arr).then(res => {
        if (!res[0].success) {
          this.$exception(res[0])
          return;
        }
        this.getWorkstationWhArea();
        this.$message.success('操作成功')
      })
    },

    delSlide(record) {
      workstationSlideDel([record.slidewayId]).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.$refs.stationTable.reload();
        } else {
          this.$exception(res)
        }
      })
    },

    showSlideModal(bool, record) {
      if (!this.clickRecord) return;
      this.whSlideVisible = true
      this.whSlideActionType = bool
      this.$nextTick(() => {
        const { form } = this.$refs.slideForm;
        if (bool) {
          form.resetFields()
        } else {
          this.whSlideRecord = record;
          form.setFieldsValue(record);
        }
      })
    },

    handleSlideOk(e) {
      const { whSlideActionType, whSlideRecord } = this
      this.$refs.slideForm.form.validateFields(async (error, values) => {
        if (!error) {
          const res = whSlideActionType
            ? await workstationSlideAdd([{ ...values, stationId: this.clickRecord.stationId, warehouseId: this.clickRecord.stationId }])
            : await workstationSlideUpload([{ ...values, slidewayId: whSlideRecord.slidewayId, stationId: this.clickRecord.stationId, warehouseId: this.clickRecord.stationId }])
          if (res.success) {
            this.whSlideVisible = false
            this.$message.success('操作成功')
            this.$refs.stationTable.reload();
          } else {
            this.$exception(res)
          }
        }
      })
    },

    handleSlideCancel(e) {
      this.whSlideVisible = false
    },





  }
}
</script>

<style lang="less" scoped>
.card-custom-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
