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

     </p-card> -->
    <a-spin :spinning="spinning" size="large" tip="数据下载中...">
      <search-table
        ref="searchTable"
        :searchItems="searchItems"
        :tableAutoLoad="false"
        tableTitle="出库监管码导出"
        :isShowBtn="false"
        tableRowKey="id"
        :tableColumns="columns"
        :tableRemoteUrl="remoteUrl"
        :tableRemoteParams="remoteParams"
        :callback="callback"
        :tableExtraBtns="tableEtraBtns"
        :tableOperators="tableOperators"
      >
      </search-table>
    </a-spin>
    <!-- <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, download, downloadALL } from './config/searchItems'
import { formItems, tableCols1, tableCols2 } from './config/modalConfig'
import { columns } from './config/columns'
import { findSrcCodes, addItem, updateItem, delItems, queryWorkstationList, uploadCircubillPC } from './api'
import { diffOption, forSelectText } from '@/views/kzyWMS/utils/index.js'
import { SERVICE_DATA_API_BASE } from '@/config/serviceSettings'
import { getCargoOwner } from '../../utils/index'

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

  data() {
    return {
      remoteUrl: { url: SERVICE_DATA_API_BASE + '/search/page', method: 'post' },
      searchItems: searchItems(this),
      columns: columns(this),
      remoteParams: { num: 'query_supervision_code4xml', params: { inBoundOrOutBound: 1, status: '10' } }, //特殊人员
      detailItem: null,
      spinning: false,
      tableEtraBtns: [
        // { label: '新增', click: () => { this.showItem() } },
        {
          label: '批量导出',
          click: () => {
            this.deleteList()
          },
        },
        {
          label: '全部导出',
          click: () => {
            this.allList()
          },
        },
      ],
      tableOperators: [
        { label: '上传', click: (record) => { this.onUp(record) } },
        // { 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
    })
  },

  mounted() {
    this.getAuthBycargoOwner()
    this.$nextTick(() => {
      let warehouse = this.$store.state.user.warehouse
      console.log(
        this.$store.state.user,
        'this.$store.state.user.warehousethis.$store.state.user.warehousethis.$store.state.user.warehouse'
      )
      this.$refs.searchTable.$refs.form.form.setFieldsValue(warehouse)
      // this.$refs.searchTable.$refs.form.form.setFieldsValue(warehouse)
    })
  },

  methods: {
    // 上传
    onUp(record) {
      let self = this
      this.$confirm({
        title: '确定要上传吗?',
        onOk() {
          uploadCircubillPC([record.refBillId]).then(res => {
            if (res.success) {
              self.$message.success(res.message)
              self.$refs.searchTable.reload()
            } else {
              self.$message.error(res.message)
            }
          })
        }
      })
    },
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.searchTable.$refs.form.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    callback(data, value) {
      data.params = { ...data.params, ...value }
      console.log(data, value, '222222222222222')
      return data
    },

    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 (this.detailItem) {
        } else {
          this.handleAdd(value)
        }
      })
      // this.$emit('input', false);
    },

    handleCancel() {
      this.detailItem = null
      this.selectedRowKeys1 = []
      this.selectedRowKeys2 = []
      this.visible = false
    },
    allList() {
      // 全部导出
      this.$refs.searchTable.$refs.form.form.validateFields((errors, values) => {
        if (!errors) {
          const datas = {
            warehouseId: values.warehouseId,
            cargoOwnerId: values.cargoOwnerId,
            supervisionType: values.supervisionType,
          }
          this.spinning = true
          downloadALL(datas, (res) => {
            this.spinning = false
          })
        }
      })
    },
    deleteList() {
      // 批量导出
      this.$refs.searchTable.$refs.form.form.validateFields(['supervisionType'], (errors, values) => {
        console.log(errors, values, 'valuesvaluesvaluesvaluesvaluesvaluesvalues')
        if (!errors) {
          // this.$refs.searchTable.reload()
          let list = this.$refs.searchTable.getSelectedItem()
          if (list.length == 0) {
            this.$message.error(this.$lang('请选择要导出的项'))
            return
          }
          console.log(list, 'listlistlist')
          let ids = []
          list.forEach((t) => (t.refBillId ? ids.push(t.refBillId) : ''))
          let newArr = [...new Set(ids)]
          if (newArr.length < 1) return this.$message.warn('您选择的单据编号不存在！')
          newArr.map((res) => {
            if (res) {
              let idsData = []
              list.map((item) => {
                if (item.refBillId == res) {
                  idsData.push(item.id)
                }
              })

              const params = {
                supervisionType: values.supervisionType,
                ids: idsData.join(','),
                // access_token: JSON.parse(localStorage.getItem("token"))
              }
              download(params)
            }
          })
        }
      })
    },

    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()
      })
    },
    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>
