<template>
  <template-page
    ref="pageRef"
    :get-list="getList"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :options-evens-group="optionsEvensGroup"
    :moreParameters="moreParameters"
    :column-parsing="columnParsing"
    :exportList="exportList"
    :operation="operation()"
  >
    <div class="cartographer_big">
      <el-dialog
        :title="formDialogTitles[formDialogType]"
        width="100%"
        :modal="false"
        :visible.sync="formDialog"
        :before-close="handleClose"
      >
        <zj-page-container>
          <zj-page-fill>
            <div style="box-sizing: border-box; padding: 20px 20px 0 20px">
              <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
                <zj-form-module title="单据信息" label-width="100px" :form-data="formData" :form-items="formItems">
                </zj-form-module>
                <zj-form-module title="商品信息" label-width="100px" :form-data="formData" :form-items="formItems2">
                </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div style="text-align: right; box-sizing: border-box; padding: 16px 20px">
            <el-button v-if="formDialogType == 0" size="mini" type="primary" @click="save">保存</el-button>
            <el-button v-if="formDialogType == 1" size="mini" type="primary" @click="save2">保存</el-button>
            <el-button v-if="formDialogType == 1" size="mini" type="primary" @click="submit">提交</el-button>
            <el-button v-if="formDialogType == 3" size="mini" type="primary" @click="examine('OK')">审核通过</el-button>
            <el-button v-if="formDialogType == 3" size="mini" type="primary" @click="examine('FAIL')"
              >审核驳回</el-button
            >
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import operation_mixin from '@/components/template/operation_mixin.js'

import {
  goodsPlanItemList,
  goodsPlanListExport,
  goodsPlanAdd,
  goodsPlanUpdate,
  goodsPlanSubmit,
  goodsPlanDetail,
  goodsPlanConfirm,
  goodsPlanDel
} from '@/api/purchaseSchedule.js'
import form_ty from './mixins/common_form'
import storage_table from './mixins/storage_table'
import storage_goods from './mixins/storage_goods'
import { delayPerform, firstPerform, intervalPerform, passivePerform, queuePerform } from 'js-perform-lock'
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin, form_ty, storage_table, storage_goods],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑', '详情', '审核'],
      formDialog: false,
      formData: {
        companyWechatId: '',
        companyWechatName: '',
        examineBy: '',
        examineTime: '',
        fileUrl: '',
        remark: '',
        status: '',
        submitBy: '',
        submitTime: '',
        totalAmount: '',
        totalQty: '',
        updateBy: '',
        updateTime: '',
        venderId: '',
        venderName: '',
        storageId: '',
        storageName: '',
        enginCode: '',
        enginName: '',
        freightAmount: '',
        orderGoodsType: '',
        fileUrl: [],
        items: []
      },
      logs: []
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm()
                this.formDialog = true
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    }
  },
  watch: {
    'formData.items': {
      handler(newVal, oldVal) {
        this.formData.totalAmount = newVal
          .filter(item => item.qty && item.price)
          .map(item => item.qty * item.price)
          .reduce((prev, cur, index, arr) => {
            return prev + cur
          }, 0)
          .toFixed(2)
      },
      deep: true
    }
  },
  methods: {
    tishicuowu: new delayPerform(500).refactor(function (/**可接收参数**/) {
      if (this.logs) {
        var logs = Array.from(
          new Set(
            JSON.parse(JSON.stringify(this.logs)).map(item => {
              return `${item.index !== undefined ? '第' + (item.index + 1) + '行：' : ''}${item.errMsg}`
            })
          )
        )
        this.logs = []
        this.$message({
          dangerouslyUseHTMLString: true,
          type: 'warning',
          message: logs.join('<div/>'),
          duration: 5000
        })
      }
    }),
    // 列表请求函数
    getList(p, cb) {
      return goodsPlanItemList(p)
    },
    // 列表导出函数
    exportList: goodsPlanListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 打开创建弹窗
    openForm() {
      this.isEditIndex = -1
      this.getGysList()
      this.getBaseList()
    },
    // 打开详情弹窗
    openDetailForm(row, type) {
      goodsPlanDetail({ id: row.id }).then(res => {
        Object.assign(this.formData, res.data, {
          fileUrl: res.data.fileUrl ? [{ url: res.data.fileUrl }] : [],
          items: res.data.items.map(item => ({ ...item, details: {} }))
        })
        this.formDialogType = type
        this.openForm()
        this.formDialog = true
      })
    },
    // 关闭弹窗
    handleClose() {
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
      this.formDialogType = 0
    },
    // 操作按钮
    operation() {
      return this.operationBtn({
        edit: {
          conditions: ({ row, index, column }) => {
            return row.status == 'SAVE'
          },
          click: ({ row, index, column }) => {
            this.openDetailForm(row, 1)
          }
        },
        del: {
          prompt: '是否确定删除',
          conditions: ({ row, index, column }) => {
            return row.status == 'SAVE'
          },
          click: ({ row, index, column }) => {
            goodsPlanDel({
              id: row.id
            }).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.$refs.pageRef.refreshList()
            })
          }
        },
        details: {
          click: ({ row, index, column }) => {
            this.openDetailForm(row, 2)
          }
        },
        examine: {
          conditions: ({ row, index, column }) => {
            return row.status == 'WAIT'
          },
          click: ({ row, index, column }) => {
            this.openDetailForm(row, 3)
          }
        }
      })
    },
    // 保存
    save() {
      this.$refs.formRef.validateField(this.getVfyKey(this.isEditIndex), (valid, invalidFields, errLabels) => {
        if (valid && this.eidtItems()) {
          goodsPlanAdd({
            ...this.formData,
            items: this.formData.items.map((item, index) => ({ ...item, index: index + 1 })),
            fileUrl: this.formData.fileUrl.map(item => item.url).join(',')
          }).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.handleClose()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    save2() {
      this.$refs.formRef.validateField(this.getVfyKey(this.isEditIndex), (valid, invalidFields, errLabels) => {
        if (valid && this.eidtItems()) {
          goodsPlanUpdate({
            ...this.formData,
            items: this.formData.items.map((item, index) => ({ ...item, index: index + 1 })),
            fileUrl: this.formData.fileUrl.map(item => item.url).join(',')
          }).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.handleClose()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    // 提交
    submit() {
      this.$refs.formRef.validateField(this.getVfyKey(this.isEditIndex), (valid, invalidFields, errLabels) => {
        if (valid && this.eidtItems()) {
          goodsPlanUpdate({
            ...this.formData,
            items: this.formData.items.map((item, index) => ({ ...item, index: index + 1 })),
            fileUrl: this.formData.fileUrl.map(item => item.url).join(',')
          }).then(res => {
            goodsPlanSubmit({
              id: this.formData.id
            }).then(res => {
              this.$message({
                type: 'success',
                message: '提交成功'
              })
              this.handleClose()
              this.$refs.pageRef.refreshList()
            })
          })
        }
      })
    },
    // 审核
    examine(type) {
      goodsPlanConfirm({
        id: this.formData.id,
        statusEnum: type
      }).then(res => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.handleClose()
        this.$refs.pageRef.refreshList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tab {
  padding: 20px 20px 0 20px;
}

::v-deep .teshudeshangchuananniu {
  color: #409eff !important;
}
</style>
