<template>
  <div>
    <!-- 货架基础资料 -->
    <p-card title="货架基础资料">
      <template slot="extra">
        <a-space>
          <!-- <p-button class="btn" type="primary">刷新</p-button> -->
          <p-button class="btn" type="primary" @click="add">添加</p-button>
          <p-upload
            name="file"
            :multiple="false"
            :headers="headers"
            :showUploadList="false"
            :action="action"
            @change="handleChange"
          >
            <p-button type="primary" style="margin-right: 10px"> <p-icon type="upload" /> 导入 </p-button>
          </p-upload>
        </a-space>
      </template>
      <p-grid-form :label-col="{ span: 8 }" :span="8" :items="config.items" @submit="hanlderSubmit" />
      <p-table
        ref="table"
        row-key="id"
        bordered
        :doneBefore="doneBefore"
        :columns="config.columns"
        :remoteUrl="config.remoteUrl"
        :remoteParams="remoteParams"
        :rowSelectType="false"
        :data-source="List"
      >
        <template slot="operation" slot-scope="text, record">
          <a @click="edit(text, record)">编辑</a>
          <a-divider v-if="text.isMode == 0" type="vertical" />
          <a v-if="text.isMode == 0" @click="setTemplateFun(text)">设为模板货架</a>
          <a-divider type="vertical" />
          <a @click="del(text)">删除</a>
        </template>
      </p-table>
    </p-card>

    <p-modal
      :title="title"
      width="50%"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p-grid-form ref="ModelForm" :span="24" :items="config.Model.items" @submit="hanlderSubmit" />
      <a-space>
        <p-button class="btn" type="primary" @click="addRow">新增行</p-button>
        <p-button class="btn" type="primary" @click="removeRow">删除行</p-button>
      </a-space>
      <p-table-sheet
        ref="tableSheet"
        dragle
        auto-width
        :scroll="{ x: true }"
        :columns="config.Model.columns"
        :dataSource="data"
        :rowSelectType="false"
        :autoLoad="false"
        bordered
      >
      </p-table-sheet>
    </p-modal>

    <p-modal
      title="设为模板货架"
      width="50%"
      :visible="visiblesetTemplate"
      :confirm-loading="confirmLoading"
      @ok="handleOkTemplate"
      @cancel="handleCancel"
    >
      <p-grid-form ref="Template" :span="24" :items="items" @submit="hanlderSubmit" />
    </p-modal>
  </div>
</template>

<script>
// import TableSheet from '@/views/kzyWMS/components/table-sheet/index.vue'
import config from './config.js'
// import { diffOption } from '@/views/kzyWMS/utils'
import { add, detail, setTemplate, palletUpdate, deletes } from './api'
const token = sessionStorage.getItem('token')
import { QN_BASEURL } from '../serviceSettings'
const baseUrl = QN_BASEURL

export default {
  components: {
    // 'p-table-sheet': TableSheet,
  },
  data() {
    return {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      action: baseUrl + '/api/v1/shelvesInfoConfig/batchImport	',
      title: '新增货架',
      config,
      data: [],
      List: [],
      detailData: {},
      type: true,
      remoteParams: {},
      visible: false,
      visiblesetTemplate: false,
      errinfo: {},
      text: {},
      confirmLoading: false,
      items: [
        {
          type: 'input',
          name: 'modeType',
          required: true,
          label: '模板货架名称',
          value: '',
        },
      ],
    }
  },
  mounted() {
    // this.getinfo()
  },
  created() {
    // diffOption(this.config.columns).then((res) => {
    //   this.config.columns = res
    // })
  },
  methods: {
    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)
      }
    },
    setTemplateFun(text) {
      this.text = text
      this.visiblesetTemplate = true
      this.$nextTick(() => {
        this.$refs.Template.form.resetFields()
      })
    },
    handleOkTemplate() {
      this.$refs.Template.form.validateFields(async (err, value) => {
        if (!err) {
          let data = {
            id: this.text?.id,
            ...value,
          }
          console.log(data)
          try {
            let res = await setTemplate(data)
            if (res.success) {
              this.visiblesetTemplate = false
              this.$message.success(res.message)
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
            }
          } catch (error) {
            this.$exception(error)
          }
        }
      })
    },

    //新增行
    addRow() {
      this.$refs.tableSheet.addRow(1, null, null, null)
    },
    removeRow() {
      //   let rowKeys = this.selectRowKeys
      //   console.log(rowKeys)
      this.$refs.tableSheet.removeSelectedRow()
    },
    //新增货架
    add() {
      this.visible = true

      this.$nextTick(() => {
        this.config.Model.items.forEach((i) => {
          i.disabled = false
        })

        this.config = { ...this.config }
        this.data = []
        this.$refs.ModelForm.form.resetFields()
      })
      this.title = '新增货架'
    },
    async edit(text, record) {
      console.log(text, record)
      this.visible = true
      this.title = '编辑货架'
      this.$nextTick(() => {
        this.config.Model.items.forEach((i) => {
          i.name == 'palletNo' && (i.disabled = true)
          i.name == 'location' && (i.disabled = true)
        })
        this.config = { ...this.config }
      })

      try {
        let res = await detail({ palletNo: text.palletNo })
        if (res.success) {
          console.log(res)
          this.data = res.data.cargoInformation
          this.$refs.ModelForm.form.setFieldsValue(res.data)
        } else {
          this.$exception(res)
        }
      } catch (error) {
        this.$exception(error)
      }
    },

    doneBefore(res) {
      //   console.log(res)
      return res
    },
    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) {
      //   ModelForm
      this.$refs.ModelForm.form.validateFields(async (err, value) => {
        if (!err) {
          console.log(value)
          try {
            let List = await this.$refs.tableSheet.getDataSource(false, true)
            console.log(List)
            value.cargoInformation = List
            console.log(value)
            if (this.title == '新增货架') {
              try {
                this.confirmLoading = true
                let res = await add(value)
                if (res.success) {
                  this.visible = false
                  this.confirmLoading = false
                  this.$message.success(res.message)
                  this.remoteParams = { ...this.remoteParams }
                } else {
                  this.confirmLoading = false
                  this.$exception(res)
                }
              } catch (error) {
                this.confirmLoading = false
                this.$exception(error)
              }
            } else {
              try {
                this.confirmLoading = true
                let res = await palletUpdate(value)
                if (res.success) {
                  this.visible = false
                  this.confirmLoading = false
                  this.$message.success(res.message)
                  this.remoteParams = { ...this.remoteParams }
                } else {
                  this.$exception(res)
                }
              } catch (error) {
                this.confirmLoading = false
                this.$exception(error)
              }
            }
          } catch (error) {
            this.confirmLoading = false
            error.message = '验证未通过'
            this.$exception(error)
          }
        }
      })
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.visiblesetTemplate = false
    },
    //点击弹出

    del(text) {
      let that = this
      console.log(text)
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        async onOk() {
          let res = await deletes({ palletNo: text.palletNo })
          if (res.success) {
            that.$message.success('删除成功')
            that.remoteParams = { ...that.remoteParams }
          } else {
            that.$exception(res)
          }
        },
        onCancel() {},
      })
    },
  },
}
</script>

<style lang="less" scoped>
.errinfo {
  padding: 10px;
  width: 100%;
  height: 200px;
  line-height: 50px;
  font-size: 20px;
  color: #fff;
  font-weight: bolder;
  text-align: center;
  background: rgb(145, 143, 144);
}
</style>
