<template>
  <search-table
      ref="table"
      :searchItems="searchItems"
      tableTitle="商品管理"
      tableRowKey="itemId"
      :tableColumns="columns"
      :tableRemoteUrl="{ url: remoteUrl, method: 'post' }"
      :tableExtraBtns="tableEtraBtns"
      :tableAutoLoad="false"
      :tableOperators="tableOperators"
  />
</template>

<script>
import SearchTable from '../../components/search-table'
import {searchItems, tableUploadBtns} from './config/searchItems'
import {columns} from './config/columns'
import {api, deleteList} from '../../api/basedata/goods'
import {sorter} from '../../utils/sort'
import {getCargoOwner} from '../../utils'
import { upcloud_base_item, upcloud_base_wh_item } from "@/config/serviceSettings";
const baseUrl = upcloud_base_item;
export default {
  components: {SearchTable},
  data() {
    return {
      tableUploadBtns: [],
      searchItems: searchItems,
      columns: null,
      remoteUrl: api.queryList,
      remoteParams: {warehouseId: this.$store.getters.warehouse.warehouseId},
      tableEtraBtns: [
        {
          label: '新增',
          vaction: 'add',
          click: () => {
            this.enterdetail()
          }
        },
        {
          label: '批量删除',
          vaction: 'batchdel',
          click: () => {
            this.deleteList()
          }
        },
        // { label: '导出', click: () => {} },
        // { label: '导入', click: () => {} },
        {
          label: '下载模板',
          click: () => {
            this.downTemplate();
          }
        },
        {
          el: 'upload',
          label: "商品ABC属性导入",
          action: baseUrl + "/itemSync/qnUpdateAbc",
          handleChange(info) {
            console.log(info, "=============");
            if (info.file.status !== "uploading") {
              console.log(info.file, info.fileList);
            }
            if (info.file.status === "done" && info.file.response.success) {
              that.$message.success(`${info.file.name} 上传成功`);
              // this.remoteParams = { ...this.remoteParams };
            } else if (info.file.status === "error") {
              that.$message.error(`${info.file.name}上传失败.`);
              that.$exception(info.file.response);
            } else if (info.file.status === "done" && !info.file.response.success) {
              that.$message.error(`${info.file.name} 上传失败`);
              that.$exception(info.file.response);
            }
          },
        },
        {
          label: '下载模板(面积)',
          click: () => {
            this.downTemplate2();
          }
        },
        {
          el: 'upload',
          label: "面积导入",
          action: baseUrl + "/itemSync/qnUpdateItemSCoe",
          handleChange(info) {
            console.log(info, "=============");
            if (info.file.status !== "uploading") {
              console.log(info.file, info.fileList);
            }
            if (info.file.status === "done" && info.file.response.success) {
              this.$message.success(`${info.file.name} 上传成功`);
              // this.remoteParams = { ...this.remoteParams };
            } else if (info.file.status === "error") {
              this.$message.error(`${info.file.name}上传失败.`);
              this.$exception(info.file.response);
            } else if (info.file.status === "done" && !info.file.response.success) {
              this.$message.error(`${info.file.name} 上传失败`);
              this.$exception(info.file.response);
            }
          },
        },
      ],
      tableOperators: [
        {
          label: '查看',
          click: record => {
            this.enterdetail(record, true)
          }
        },
        {
          label: '修改',
          vaction: 'update',
          click: record => {
            this.enterdetail(record)
          }
        }
        // { label: '删除', click: (record) => { this.deleteItem(record) } },
      ]
    }
  },
  created() {
    this.columns = sorter(columns)
    this.$nextTick(() => {
      this.$refs.table.$refs.form.form.setFieldsValue({
        warehouseId: this.$store.getters.warehouse.warehouseId
      })
      this.getCargoOwnerFirst()
    })
  },
  methods: {
    downTemplate() {
      this.axios({
        method: "get",
        url: baseUrl + "/itemSync/downloadTemplate",
        headers: { "Content-Type": "application/json" },
        // data: JSON.stringify(this.exportData.exportParams),s
        responseType: "blob",
      })
        .then((_res) => {
          let blob = new Blob([_res]);
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "ABC属性.xls"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        })
        .finally(() => {
          //   this.iconLoading = false;
        });
    },
    downTemplate2() {
      this.axios({
        method: "get",
        url: baseUrl + "/itemSync/downloadsCoeTem",
        headers: { "Content-Type": "application/json" },
        // data: JSON.stringify(this.exportData.exportParams),s
        responseType: "blob",
      })
        .then((_res) => {
          let blob = new Blob([_res]);
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "面积.xls"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        })
        .finally(() => {
          //   this.iconLoading = false;
        });
    },
    enterdetail(item, isView) {
      this.$emit('changeStep', {step: 2, item: item, isView: isView})
    },
    deleteItem(item) {
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete(item.itemId)
        }
      })
    },
    deleteList() {
      let list = this.$refs.table.getSelectedItem()
      if (list.length == 0) {
        this.$message.error(this.$lang('请选择要删除的项'))
        return
      }
      let ids = []
      list.forEach(t => ids.push(t.itemId))
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete(ids.join(','))
        }
      })
    },
    handleDelete(ids) {
      return deleteList({itmeIds: ids}).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        this.$refs.table.reload()
        this.$message.success(this.$lang('删除成功'))
      })
    },
    //获取货主信息
    getCargoOwnerFirst() {
      getCargoOwner().then(res => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$nextTick(() => {
          if (res.data.list.length > 0) {
            this.$refs.table.$refs.form.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerCode: res.data.list[0].companyCode,
              cargoOwnerName: res.data.list[0].companyName
            })
          }
        })
      })
    }
  }
}
</script>

<style></style>
