<template>
  <div>
    <p-card
      style="width: 100%"
      :tab-list="tabListNoTitle"
      :active-tab-key="noTitleKey"
      @tabChange="(key) => onTabChange(key, 'noTitleKey')"
    >
      <div v-if="noTitleKey === 'article'">
        <Freight />
      </div>

      <div v-else-if="noTitleKey === 'app'">
        <!-- <p-card title="货位资料"> -->
        <!-- <span slot="extra"> -->
        <!-- <p-button type="primary" style="margin-right:10px" @click="showmodel()">添加</p-button> -->
        <div style="overflow: hidden">
          <!-- <p-button type="primary" style="margin-right:10px"> <p-icon type="upload" />导入货位</p-button> -->
          <p-button type="primary" style="margin-right: 10px; float: right" @click="computeAllLocator">
            计算所有货位</p-button
          >
          <a-dropdown style="float: right">
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1">
                <p-upload
                  name="file"
                  :multiple="false"
                  action="/api/upcloud-base-wh-dev-mysql-eistest/eisLocator/save-goods-excel"
                  :headers="headers"
                  @change="handleChange"
                >
                  <p-button type="primary"> 上传模板</p-button>
                </p-upload>
              </a-menu-item>

              <a-menu-item key="2">
                <p-button type="primary" @click="handLoad"> 下载模板</p-button>
              </a-menu-item>
            </a-menu>
            <!-- <a-button style="margin-left: 8px"> Button <a-icon type="down" /> </a-button> -->
            <p-button type="primary" style="margin-right: 10px"> <p-icon type="upload" />导入货位</p-button>
          </a-dropdown>
        </div>

        <!-- </span> -->
        <p-grid-form :label-col="{ span: 8 }" :span="8" :items="config.items" @submit="hanlderSubmit" />
        <p-table
          ref="table"
          row-key="id"
          bordered
          :columns="config.columns"
          :remoteUrl="config.remoteUrl"
          :remoteParams="remoteParams"
          :rowSelectType="false"
          :data-source="data"
        >
          <template slot="groupNo" slot-scope="text, record">
            <!-- <a @click="showmodeladjust(record)">{{ text }}</a> -->
            <a @click="showmodeladjust(record)">{{ text }}</a>
            <!-- <span v-else>{{ text }}</span> -->
          </template>
          <template slot="operation" slot-scope="text, record">
            <!-- {{ text ? '禁用' : '启用' }} -->
            <a @click="showmodelLock(record)">调整货位组锁</a>
            <a-divider type="vertical" />
            <a @click="showmodel(record)">修改</a>
          </template>
        </p-table>
        <!-- </p-card> -->

        <p-modal
          title="修改货位资料"
          width="50%"
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <p-grid-form
            :label-col="{ span: 8 }"
            ref="model1"
            :span="8"
            :items="config.Modelitems"
            @submit="hanlderSubmit"
          />
        </p-modal>

        <p-modal
          title="详情"
          width="50%"
          :visible="visibleLock"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <p-grid-form
            :label-col="{ span: 8 }"
            ref="model2"
            :span="8"
            :items="config.ModelitemsLock"
            @submit="hanlderSubmit"
          />
        </p-modal>

        <p-modal
          title="详情"
          width="50%"
          :visible="visibleadjust"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
          :footer="null"
        >
          <p-grid-form
            :label-col="{ span: 8 }"
            ref="model3"
            :span="8"
            :items="config.Modelitemsadjust"
            @submit="hanlderSubmit"
          />
          <div class="btn">
            <p-button v-if="modifybtn" type="primary" @click="ModifyModel">修改</p-button>
            <p-button v-else type="primary" @click="btnSave">保存</p-button>
            <p-button type="primary" @click="handleCancel">取消</p-button>
            <p-button type="primary" @click="recalibrate">重新校准</p-button>
          </div>
        </p-modal>
      </div>
    </p-card>

    <!-- 货位资料 -->
  </div>
</template>

<script>
import config from './config.js'

import {
  add,
  deletes,
  update,
  adjustupdate,
  groupupdate,
  goodsget,
  recalibrateApi,
  downloadLocatorTemplate,
  computeAllLocatorApi,
} from './api'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
const token = sessionStorage.getItem('token')
// console.log(token)
import Freight from './warehouse/Freight.vue'
export default {
  components: {
    Freight,
  },
  data() {
    return {
      modifybtn: true,
      tabListNoTitle: [
        {
          key: 'article',
          tab: '货位资料主数据',
        },
        {
          key: 'app',
          tab: '货位资料',
        },
      ],
      key: 'tab1',
      noTitleKey: 'app',
      config,
      data: [],
      type: true,
      remoteParams: {
        areaNo: '',
        endtime: '',
        starttime: '',
        stationNo: '',
        type: '',
      },
      visible: false,
      visibleLock: false,
      visibleadjust: false,
      confirmLoading: false,
      headers: {
        Authorization: `Bearer ${token}`,
      },
    }
  },
  mounted() {
    // this.getinfo()
  },
  methods: {
    //计算所有货位
    async computeAllLocator() {
      let res = await computeAllLocatorApi()
      console.log(res)
      if (res.success) {
        this.$message.success(res.message)
        // this.handleCancel()
        // this.remoteParams = { ...this.remoteParams }
      } else {
        this.$exception(res)
      }
    },
    handLoad() {
      this.download('货位模板')
    },
    async download(name) {
      //   const ele = document.createElement('a')
      //   ele.setAttribute('href', '/api/upcloud-base-wh-control-mysql-eistest/eisLocator/downloadLocatorTemplate/')
      //   //this.$options.filters['filterUrl']是调用全局过滤器,filterUrl是你自己项目main.js里面定义的过滤器
      //   ele.setAttribute('download', name)
      //   ele.style.display = 'none'
      //   document.body.appendChild(ele)
      //   ele.click()
      //   document.body.removeChild(ele)

      let res = await downloadLocatorTemplate()
      console.log(res)
      const content = res
      const blob = new Blob([content])
      var date = new Date().getFullYear() + '' + (new Date().getMonth() + 1) + '' + new Date().getDate()
      const fileName = date + name + '.xls'
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    },

    handleMenuClick(e) {
      console.log('click', e)
    },
    //保存
    btnSave() {
      this.$refs.model3.form.validateFields(async (err, values) => {
        //   console.log(err, values)
        if (!err) {
          console.log(values)
          let res = await groupupdate(values)
          console.log(res)
          if (res.success) {
            this.$message.success(res.message)
            this.handleCancel()
            this.remoteParams = { ...this.remoteParams }
          } else {
            this.$exception(res)
          }
        }
      })
    },
    //重新校准
    async recalibrate() {
      let res = await recalibrateApi(this.locatorGroup)
      console.log(res)
      if (res.success) {
        this.remoteParams = { ...this.remoteParams }
        this.$message.success(res.message)
      } else {
        this.$exception(res)
      }
    },
    //修改弹窗
    ModifyModel() {
      this.config.Modelitemsadjust.forEach((item) => {
        if (item.name != 'locationNum') {
          item.disabled = false
        }

        this.modifybtn = false
      })
    },
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
    },

    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)
      }
    },
    hanlderSubmit(e, form) {
      e.preventDefault()
      form.validateFields((error, values) => {
        console.log(error, values, 'valuesvaluesvaluesvaluesvalues')
        // this.queryName = values.name
        // this.queryType = values.type
        // this.getlistCompanyByAuthId()
        if (!error) {
          this.remoteParams = { ...this.remoteParams, ...values }
        }
      })
    },
    handleOk(e) {
      //   this.$refs.model1.form.validateFields(async (err, value) => {
      //         })

      this.confirmLoading = true
      console.log(this.type)
      if (this.type == 1) {
        //修改
        this.$refs.model1.form.validateFields(async (err, value) => {
          if (!err) {
            console.log(value)
            value.id = value.locatorGroupId
            let res = await update(value)
            console.log(res)
            if (res.success) {
              this.$message.success(res.message)
              //   this.visible = false
              this.handleCancel()
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
            }
          }
        })
      } else if (this.type == 2) {
        //新增
        this.$refs.model1.form.validateFields(async (err, value) => {
          if (!err) {
            let res = await add(value)
            console.log(res)
            if (res.success) {
              this.$message.success(res.message)
              //   this.visible = false
              this.handleCancel()
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
            }
          }
        })
      } else if (this.type == 3) {
        //调整货位组锁
        this.$refs.model2.form.validateFields(async (err, value) => {
          if (!err) {
            value.id = value.locatorGroupId
            let res = await adjustupdate(value)
            console.log(res)
            if (res.success) {
              this.$message.success(res.message)
              //   this.visible = false
              this.handleCancel()
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
            }
          }
        })
      } else if (this.type == 4) {
        this.$refs.model3.form.validateFields(async (err, value) => {
          if (!err) {
            //   value.id = value.locatorGroupId
            console.log(value, '====')
            let res = await groupupdate(value)
            console.log(res)
            if (res.success) {
              this.$message.success(res.message)
              this.handleCancel()
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
            }
          }
        })
      }

      this.confirmLoading = false
      //
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.visibleLock = false
      this.modifybtn = true
      this.config.Modelitemsadjust.forEach((item) => {
        item.disabled = true
      })
      this.visibleadjust = false
    },
    //点击
    //调整货位租锁
    showmodelLock(data) {
      console.log(data)
      //   this.config.Modelitems = config.ModelitemsLock
      this.type = 3
      this.visibleLock = true
      this.$nextTick(() => {
        this.$refs.model2.form.setFieldsValue(data)
        // this.$refs.model2.form.setFieldsValue(data)
      })
    },

    //修改货位组资料
    async showmodeladjust(data) {
      console.log(data)
      let res = await goodsget({ id: data.locatorGroupId })
      console.log(res)
      if (res.success) {
        let datas = res.data
        console.log(datas)
        this.locatorGroup = res.data
        this.type = 4
        this.visibleadjust = true
        this.$nextTick(() => {
          this.$refs.model3.form.setFieldsValue(datas)
        })
      } else {
        this.$exception(res)
      }
    },
    //修改
    showmodel(data) {
      console.log(data)
      //   this.config.Modelitems = config.Modelitems0
      this.visible = true
      if (data) {
        //修改
        this.$nextTick(() => {
          //   this.$refs.model1.form.setFieldsValue(data)
          this.$refs.model1.form.setFieldsValue(data)
        })
        this.type = 1
      } else {
        //新增
        this.$nextTick(() => {
          this.$refs.model1.form.resetFields()
        })
        this.type = 2
      }
    },
    del(text) {
      let that = this
      console.log(text)
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        async onOk() {
          let res = await deletes({ id: text.id })
          if (res.success) {
            that.$message.success('删除成功')
            that.remoteParams = { ...that.remoteParams }
          } else {
            that.$exception(res)
          }
        },
        onCancel() {},
      })
    },
  },
}
</script>

<style lang="less" scoped>
.btn {
  display: flex;
  justify-content: space-around;
}
</style>
