<template>
  <div>
    <a-spin :spinning="spinning" size="large" tip="数据下载中...">
      <search-table
        ref="searchTable"
        :searchItems="searchItems"
        :tableAutoLoad="false"
        tableTitle="入库监管码导出"
        tableRowKey="id"
        :isShowBtn="false"
        :tableColumns="columns"
        :tableRemoteUrl="remoteUrl"
        :tableRemoteParams="remoteParams"
        :callback="callback"
        :tableExtraBtns="tableEtraBtns"
        :tableOperators="tableOperators"
      >
      </search-table>
    </a-spin>
  </div>
</template>

<script>
import SearchTable from '../../components/search-table'
import { searchItems, download, downloadALL } from './config/searchItems'
// import { loadXMLDoc } from "./config/xml";
import { columns } from './config/columns'
import { findSrcCodes, addItem, updateItem, delItems, queryWorkstationList, outboundExport, uploadCircubillPC } from './api'
import { diffOption, forSelectText } from '@/views/kzyWMS/utils/index.js'
import { sorter } from '../../utils/sort'
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: { supervisionType: 0, status: '10' } }, //特殊人员
      detailItem: null,
      spinning: false,
      tableEtraBtns: [
        // { label: '新增', click: () => { this.showItem() } },
        {
          label: '批量导出',
          click: () => {
            this.deleteList()
          },
        },
        {
          label: '全部导出',
          click: () => {
            this.allList()
          },
        },
      ],
      tableOperators: [
        // { label: '修改', click: (record) => { this.showItem(record) } },
        { label: '上传', click: (record) => { this.onUp(record) } },
        { label: '删除', click: (record) => { this.onDel(record) } },
      ],
      // modal
      visible: false,
      warehouseId: '',
      queryWarehouseId: '',
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) {
          this.warehouseId = ''
        }
      },
    },
  },

  created() {
    diffOption(columns(this)).then((res) => {
      this.columns = sorter(res)
    })
  },

  mounted() {
    this.getAuthBycargoOwner()
    this.$nextTick(() => {
      let warehouse = this.$store.state.user.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)
            }
          })
        }
      })
    },
    // 删除
    onDel(record) {
      let self = this
      this.$confirm({
        title: '确定要删除吗?',
        onOk() {
          delItems({Id:record.id}).then(res => {
            console.log(res, '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 }
      return data
    },
    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)
            }
          })
        }
      })
    },
  },
}
</script>

<style></style>
