<template>
  <template-page v-if="pageShow" ref="pageRef" :get-list="getList" :table-attributes="tableAttributes"
    :table-events="tableEvents" :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters"
    :column-parsing="columnParsing" :exportList="exportList" :operation="operation()" key="pageType">
    <div slot="moreSearch">
      <el-radio-group v-model="pageType" size="mini" @change="changePageType">
        <el-radio-button label="list">列表</el-radio-button>
        <el-radio-button label="goodsder">商品明细</el-radio-button>
        <el-radio-button label="codeder">条码明细</el-radio-button>
      </el-radio-group>
      <br /><br />
    </div>
    <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">
                  <el-tabs slot="header" v-model="activeName">
                    <el-tab-pane label="商品信息" name="goodsInfo"></el-tab-pane>
                    <el-tab-pane v-if="formDialogType > 0 && joinCode" label="条码信息" name="codeInfo"></el-tab-pane>
                  </el-tabs>
                </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div v-if="activeName == 'goodsInfo'" 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="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 {
  goodsPurchaseRetList,
  goodsPurchaseRetListExport,
  goodsPurchaseRetItemList,
  goodsPurchaseRetItemListExport,
  goodsPurchaseRetCodeList,
  goodsPurchaseRetCodeListExport,
  goodsPurchaseRetAdd,
  goodsPurchaseRetSubmit,
  goodsPurchaseRetConfirm,
  goodsPurchaseRetDetail,
  goodsPurchaseRetDel
} from '@/api/merchandisePurchaseReturn.js'
import form_ty from '../mixins/common_form'
import out_storage_table from '../mixins/out_storage_table'
import out_storage_goods from '../mixins/out_storage_goods'
import out_storage_codes from '../mixins/out_storage_codes'
import common from '../mixins/common_code'
import { delayPerform, firstPerform, intervalPerform, passivePerform, queuePerform } from "js-perform-lock";
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin, form_ty, out_storage_table, out_storage_goods, out_storage_codes, common],
  data() {
    return {
      pageType: 'list',
      pageShow: true,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增退货单', '编辑退货单', '退货单详情', '审核退货单'],
      formDialog: false,
      appraise_status: '',
      formData: {
        companyWechatId: '',
        companyWechatName: '',
        examineBy: '',
        examineTime: '',
        fileUrl: [],
        goodsPurchaseId: '',
        items: [],
        remark: '',
        status: '',
        submitBy: '',
        submitTime: '',
        totalAmount: '',
        totalQty: '',
        venderId: '',
        venderName: '',
        codeInfoList: []
      },
      activeName: 'goodsInfo',
      goods_material_id: '',
      joinCode: false,
	  joinCodeText: JSON.parse(localStorage.getItem('greemall_user')).joinCode,
      logs:[]
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      if (this.pageType == 'list') {
        return [
          [
            [
              this.optionsEvensAuth('add', {
                click: () => {
                  this.formDialog = true
                  this.openForm()
                }
              })
            ]
          ]
        ]
      } else if (this.pageType == 'goodsder') {
        return []
      } else if (this.pageType == 'codeder') {
        return []
      }
    },
    // 更多参数
    moreParameters() {
      return []
    }
  },
  watch: {
    pageType() {
      this.handleClose()
      this.pageShow = false
      this.$nextTick(() => {
        this.pageShow = 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,
        });
      }
    }),
    changePageType() {
      this.goods_material_id = ''
    },
    // 列表请求函数
    getList(p, cb) {
      if (this.pageType == 'list') {
        return goodsPurchaseRetList(p)
      } else if (this.pageType == 'goodsder') {
        return goodsPurchaseRetItemList(p)
      } else if (this.pageType == 'codeder') {
        if (this.goods_material_id) {
          return goodsPurchaseRetCodeList({
            ...p,
            params: [...p.params, { param: 'b.goods_material_id', compare: '=', value: this.goods_material_id }]
          })
        } else {
          return goodsPurchaseRetCodeList(p)
        }
      }
    },
    // 列表导出函数
    exportList(...p) {
      if (this.pageType == 'list') {
        return goodsPurchaseRetListExport(...p)
      } else if (this.pageType == 'goodsder') {
        return goodsPurchaseRetItemListExport(...p)
      } else if (this.pageType == 'codeder') {
        return goodsPurchaseRetCodeListExport(...p)
      }
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 打开创建弹窗
    openForm() {
      this.isEditIndex = -1
      this.getGysList()
	  this.getWarehouseList()
      this.getCgrkOrder()
    },
    // 打开详情弹窗
    openDetailForm(row, type) {
      goodsPurchaseRetDetail({ 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
      this.activeName = 'goodsInfo'
      this.joinCode = false
    },
    // 操作按钮
    operation() {
      if (this.pageType == 'list') {
        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 }) => {
              goodsPurchaseRetDel({
                id: row.id
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.$refs.pageRef.refreshList()
              })
            }
          },
          detail: {
            click: ({ row, index, column }) => {
              this.openDetailForm(row, 2)
            }
          },
          shenhe: {
            conditions: ({ row, index, column }) => {
              return row.status == 'WAIT'
            },
            click: ({ row, index, column }) => {
              this.openDetailForm(row, 3)
            }
          }
        })
      } else if (this.pageType == 'goodsder') {
        return this.operationBtn({
          codeDetail: {
            click: ({ row, index, column }) => {
              this.goods_material_id = row.goodsMaterialId
              this.pageType = 'codeder'
            }
          }
        })
      } else if (this.pageType == 'codeder') {
        return undefined
      }
    },
    // 保存
    save() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          goodsPurchaseRetAdd({
            ...this.formData,
            items: this.formData.items.map((item, index) => ({ ...item, index: index + 1 })),
            fileUrl: this.formData.fileUrl.map(item => item.url).join(','),
            codeInfoList: undefined
          }).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.handleClose()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    // 提交
    submit() {
      goodsPurchaseRetSubmit({
        id: this.formData.id
      }).then(res => {
        this.$message({
          type: 'success',
          message: '提交成功'
        })
        this.handleClose()
        this.$refs.pageRef.refreshList()
      })
    },
    // 审核
    examine(type) {
      goodsPurchaseRetConfirm({
        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>
