<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <template-page
        v-if="activeKey == 'list'"
        ref="pageRef"
        :get-list="getList"
        :table-attributes="tableAttributes"
        :table-events="tableEvents"
        :options-evens-group="optionsEvensGroup"
        :moreParameters="moreParameters"
        :column-parsing="columnParsing"
        :operation="operation()"
        :exportList="exportList"
      >
      </template-page>
      <div v-if="~['add', 'examine', 'detail'].indexOf(activeKey)">
        <div style="box-sizing: border-box; padding: 20px">
          <zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
            <zj-form-module
              title="单据信息"
              label-width="100px"
              :showPackUp="false"
              :form-data="formData"
              :form-items="formItems"
            >
            </zj-form-module>
            <zj-form-module
              title="产品信息"
              label-width="100px"
              :showPackUp="false"
              :form-data="formData"
              :form-items="formItems2"
            >
            </zj-form-module>
          </zj-form-container>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="data.removeTab()">取 消</el-button>
            <el-button v-if="formDialogType !== 2" size="mini" @click="formSubmit(data.removeTab)" type="primary"
              >保 存</el-button
            >
            <el-button v-if="formDialogType == 1" size="mini" @click="formConfirm(data.removeTab)" type="primary"
              >审 核</el-button
            >
          </div>
        </div>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import {
  goodsMoveList,
  goodsMoveListExport,
  goodsMoveAdd,
  goodsMoveDetail,
  goodsMoveConfirm,
  goodsMoveSubmit,
  goodsMoveUpdate,
  goodsMoveItemImportCode,
  goodsMoveDel,
  goodsMoveItemAddCode,
  goodsMoveItemDelCode,
  goodsMoveQueryExistStorageBrand,
  goodsMoveQueryExistStorageCategory,
  goodsMoveQueryExistStorageGoods,
  goodsMoveQueryExistStorageGoodsNum
} from '@/api/GoodsTransferPeceipt'
import ImageUpload from '@/components/file-upload'
import operation_mixin from '@/components/template/operation_mixin.js'
import editTable from '@/components/template/editTable.js'
import { getWebsit } from '@/api/customerManagement.js'
import { storageListPageV2 } from '@/api/storage'
import { materialCategoryList } from '@/api/auxiliaryMaterialClass'
import storage_goods from './storage_goods.js'
import storage_table from './storage_table.js'
export default {
  components: { TemplatePage, ImageUpload },
  mixins: [import_mixin, operation_mixin, storage_goods, storage_table],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '审核', '查看'],
      formData: {
        companyWechatId: '',
        companyWechatName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
        examineBy: '',
        examineTime: '',
        inStorageId: '',
        inStorageName: '',
        items: [],
        outStorageId: '',
        outStorageName: '',
        remark: '',
        status: '',
        submitBy: '',
        submitTime: '',
        totalQty: '',
        type: 'G',
        websitId: '',
        websitName: ''
      },
      websitSelectList: [],
      warehouseList: []
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          md: 6,
          isShow: true,
          name: 'el-select',
          options: [
            { label: '保存', value: 'SAVE' },
            { label: '待审核', value: 'WAIT' },
            { label: '通过', value: 'OK' },
            { label: '失败', value: 'FAIL' }
          ],
          attributes: { disabled: true },
          formItemAttributes: {
            label: '单据状态',
            prop: 'status',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '', disabled: true },
          formItemAttributes: {
            label: '单据编号',
            prop: 'id',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '所属商户',
            prop: 'companyWechatName',
            rules: []
          }
        },
        // {
        //   md: 6,
        //   isShow: true,
        //   name: 'el-select',
        //   options: this.websitSelectList.map(item => ({ label: item.name, value: item.websitId })),
        //   attributes: {},
        //   formItemAttributes: {
        //     label: '网点名称',
        //     prop: 'websitId',
        //     rules: [...required]
        //   }
        // },
        {
          md: 6,
          name: 'el-radio',
          options: [
            { label: '商品', value: 'G' }
            // { label: '辅材', value: 'M' },
            // { label: '辅材', value: 'P' }
          ],
          attributes: {
            disabled: this.formDialogType == 2
          },
          formItemAttributes: {
            label: '调仓产品',
            prop: 'type',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-select',
          options: this.warehouseList
            .map(item => ({ label: item.storageName, value: item.storageId }))
            .filter(item => item.value !== this.formData.inStorageId),
          attributes: {
            disabled: this.formDialogType == 2
          },
          formItemAttributes: {
            label: '调出仓库',
            prop: 'outStorageId',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-select',
          options: this.warehouseList
            .map(item => ({ label: item.storageName, value: item.storageId }))
            .filter(item => item.value !== this.formData.outStorageId),
          attributes: {
            disabled: this.formDialogType == 2
          },
          formItemAttributes: {
            label: '调入仓库',
            prop: 'inStorageId',
            rules: [...required]
          }
        },
        {
          md: 12,
          isShow: true,
          name: 'slot-component',
          attributes: { placeholder: '' },
          formItemAttributes: {
            label: '',
            prop: '',
            'label-width': '0px'
          },
          render: (h, { props, onInput }) => {
            return <div></div>
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '制单人',
            prop: 'createBy',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '制单时间',
            prop: 'createTime',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '审核人',
            prop: 'examineBy',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '审核时间',
            prop: 'examineTime',
            rules: []
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'textarea', rows: 5, disabled: this.formDialogType == 2 },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: goodsMoveList,
    // 列表导出函数
    exportList: goodsMoveListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        view: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openForm('detail', row.id)
          }
        },
        examine: {
          btnType: 'text',
          conditions: ({ row, index, column }) => {
            return row.status !== 'OK'
          },
          click: ({ row, index, column }) => {
            this.openForm('examine', row.id)
          }
        }
      })
    },
    // 取消 新增编辑
    formCancel() {
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },
    // 打开 新增编辑 网点表单
    openForm(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { examine: '审核', add: '新增', detail: '查看' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.formCancel()
          this.$nextTick(() => {
            if (type == 'add') {
              this.formDialogType = 0
              this.initData()
            } else if (type == 'examine') {
              this.formDialogType = 1
              goodsMoveDetail({ id }).then(res => {
                Object.assign(this.formData, res.data)
                this.initData()
              })
            } else {
              this.formDialogType = 2
              goodsMoveDetail({ id }).then(res => {
                Object.assign(this.formData, res.data)
                this.initData()
              })
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    initData() {
      this.getBaseList()
      Promise.all([
        getWebsit({ type: 'C', status: true }),
        storageListPageV2({
          pageNum: 1,
          pageSize: -1,
          params: [
            { param: 'a.type', compare: 'like', value: '商品' },
            { param: 'a.status', compare: '=', value: 'true' }
          ]
        })
      ]).then(([res1, res2]) => {
        this.websitSelectList = res1.data
        this.warehouseList = res2.data.records
      })
    },
    formSubmit(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formDialogType == 0) {
            goodsMoveAdd({ ...this.formData }).then(res => {
              this.$message({
                type: 'success',
                message: `保存成功!`
              })
              cancel('list')
              this.$refs.pageRef.refreshList()
            })
          } else if (this.formDialogType == 1) {
            goodsMoveUpdate({ ...this.formData }).then(res => {
              this.$message({
                type: 'success',
                message: `保存成功!`
              })
              cancel('list')
              this.$refs.pageRef.refreshList()
            })
          }
        }
      })
    },
    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formData.status == 'WAIT') {
            goodsMoveConfirm({ id: this.formData.id, statusEnum: 'OK' }).then(res => {
              this.$message({
                type: 'success',
                message: `审核成功!`
              })
              cancel('list')
              this.$refs.pageRef.refreshList()
              // 备注
            })
          } else {
            goodsMoveUpdate({ ...this.formData }).then(res => {
              goodsMoveSubmit({ id: this.formData.id }).then(res => {
                goodsMoveConfirm({ id: this.formData.id, statusEnum: 'OK' }).then(res => {
                  this.$message({
                    type: 'success',
                    message: `审核成功!`
                  })
                  cancel('list')
                  this.$refs.pageRef.refreshList()
                  // 备注
                })
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
