<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{activeKey, data}">
      <div :style="{
    width: '100%',
    height: activeKey == 'list' ? '100%' : '0px',
    overflow: 'hidden'
  }">
        <template-page v-if="isShowTab" 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 slot="moreSearch">
            <el-radio-group v-model="flag" size="mini">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="SAVE">保存</el-radio-button>
              <el-radio-button label="SUBMIT">提交</el-radio-button>
              <el-radio-button label="OK">通过</el-radio-button>
              <el-radio-button label="FAIL">失败</el-radio-button>
            </el-radio-group>
            <br><br>
          </div>
        </template-page>
      </div>
      <div v-if="~['add', 'edit', 'detail', 'confirm'].indexOf(activeKey)" style="box-sizing: border-box;padding: 16px;">
        <div>
          <zj-form-container ref="formRef" :form-data="formData">
            <zj-form-module title="单据信息" :form-data="formData" :form-items="formItems">
            </zj-form-module>
            <zj-form-module title="旧件信息" :form-data="formData" :form-items="product">
            </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="openType == 0 || formData.flag == 'SAVE'" size="mini" type="primary"
              @click="quedingbaocun(data.removeTab)">{{formData.flag == 'SAVE'?'提交':'保存'}}</el-button>
            <el-button v-if="openType == 3 && formData.flag == 'SUBMIT'" size="mini" type="primary"
              @click="shenbi(data.removeTab, 'OK')">审核通过</el-button>
            <el-button v-if="openType == 3 && formData.flag == 'SUBMIT'" size="mini" type="primary"
              @click="shenbi(data.removeTab, 'FAIL')">审核失败</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 operation_mixin from '@/components/template/operation_mixin.js'
import basicInfo from "./mixins/basicInfo"
import productColumns from "./mixins/productColumns"
import { websitPartsFactoryRetListPageV2, websitPartsFactoryRetPageExport, websitPartsFactoryRetDetail, websitPartsFactoryRetAdd, websitPartsFactoryRetUpdate, websitPartsFactoryRetExamine } from "@/api/oldPartsReturnFactory";
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin, basicInfo, productColumns],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      openType: 0,
      formData: {
        "address": "",
        "area": "",
        "areaId": "",
        "buyPeople": "",
        "city": "",
        "cityId": "",
        "companyWechatId": "",
        "companyWechatName": JSON.parse(localStorage.getItem('greemall_user')).companyName,
        "endTime": "",
        "factory": "",
        "factoryAddress": "",
        "fileUrl": [],
        "flag": "",
        "goodsType": "P",
        "identity": "",
        "manger": "",
        "mobile": "",
        "orderEnginBaseId": "",
        "orderUseType": "",
        "partsRetId": "",
        "payNo": "",
        "payTime": "",
        "payType": "",
        "projectName": "",
        "projectNo": "",
        "province": "",
        "provinceId": "",
        "reason": "",
        "refundSerialNo": "",
        "refundState": "",
        "refundTime": "",
        "remark": "",
        "salesId": "",
        "salesTime": "",
        "salesType": "",
        "source": "",
        "startTime": "",
        "street": "",
        "streetId": "",
        "submitBy": "",
        "submitTime": "",
        "totalAmount": 0,
        "totalRefundAmount": 0,
        "type": "FACTORY",
        "websitId": "",
        "websitName": "",
        "websitPartsRetItemList": [],
        "websitPartsRetItems": [],
        "websitPartsRetOldRecordList": [],
        "workerId": "",
        "workerMobile": "",
        "workerName": "",
        "workerWebsitId": "",
        "workerWebsitName": ""
      },
      isShowTab: true,
      flag: ""
    }
  },
  computed: {
    // 更多参数
    moreParameters() {
      return []
    },
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.$refs.tabPage.addTab({
                  // 对应显示的模块
                  activeKey: "add",
                  // 唯一标识
                  key: "add",
                  // 页签名称
                  label: "新增",
                  // 打开时事件
                  triggerEvent: () => {
                    this.handleClose()
                    this.$nextTick(() => {
                      this.openForm()
                    })
                  },
                  // 关闭时事件
                  closeEvent: () => { }
                })
              }
            })
          ]
        ]
      ]
    },
  },
  watch: {
    flag() {
      this.isShowTab = false
      this.$nextTick(() => {
        this.isShowTab = true
      })
    }
  },
  methods: {
    // 列表请求函数
    getList(p, cb) {
      try {
        var pam = JSON.parse(JSON.stringify(p))
        if (this.flag) {
          pam.params.push({ 'param': 'a.flag', "compare": "=", "value": this.flag })
        }
        cb && cb(pam)
        return websitPartsFactoryRetListPageV2(pam)
      } catch (error) {
        console.log(error)
      }
    },
    // 列表导出函数
    exportList: websitPartsFactoryRetPageExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 关闭
    handleClose() {
      this.$data.formData = this.$options.data().formData
      this.openType = 0
    },
    // 打开弹窗
    openForm() {
      this.getWebsitList()
      this.getProductSel()
    },
    // 保存
    quedingbaocun(removeTab) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ; ([websitPartsFactoryRetAdd, websitPartsFactoryRetUpdate][this.formData.partsRetId ? 1 : 0])({
            ...this.formData,
            ...(() => {
              if (this.formData.partsRetId) {
                return {
                  flag: "SUBMIT"
                }
              }
            })(),
            fileUrl: this.formData.fileUrl.map(item => item.url).join(",")
          }).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.$refs.pageRef.refreshList()
            removeTab && removeTab()
            this.handleClose()
          })
        }
      })
    },
    shenbi(removeTab, flag) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          websitPartsFactoryRetExamine({
            ...this.formData,
            fileUrl: this.formData.fileUrl.map(item => item.url).join(","),
            flag: flag
          }).then(res => {
            this.$message({
              type: 'success',
              message: '审核成功'
            })
            this.$refs.pageRef.refreshList()
            removeTab && removeTab()
            this.handleClose()
          })
        }
      })
    },
    // 操作按钮
    operation() {
      return this.operationBtn({
        detail: {
          click: ({ row, index, column }) => {
            this.$refs.tabPage.addTab({
              // 对应显示的模块
              activeKey: "detail",
              // 唯一标识
              key: "detail",
              // 页签名称
              label: "详情",
              // 打开时事件
              triggerEvent: () => {
                this.handleClose()
                this.$nextTick(() => {
                  this.openType = 1;
                  websitPartsFactoryRetDetail({ id: row.partsRetId }).then(res => {
                    Object.assign(this.formData, res.data, {
                      fileUrl: res.data.fileUrl ? res.data.fileUrl.split(",").map(url => ({ url })) : [],
                      websitPartsRetItems: res.data.websitPartsRetItemList
                    })
                    this.openForm()
                  })
                })
              },
              // 关闭时事件
              closeEvent: () => { }
            })
          }
        },
        edit: {
          conditions: ({ row, index, column }) => {
            return row.flag == 'SAVE'
          },
          click: ({ row, index, column }) => {
            this.$refs.tabPage.addTab({
              // 对应显示的模块
              activeKey: "edit",
              // 唯一标识
              key: "edit",
              // 页签名称
              label: "编辑",
              // 打开时事件
              triggerEvent: () => {
                this.handleClose()
                this.$nextTick(() => {
					this.openType = 2;
                  websitPartsFactoryRetDetail({ id: row.partsRetId }).then(res => {
                    Object.assign(this.formData, res.data, {
                      fileUrl: res.data.fileUrl ? res.data.fileUrl.split(",").map(url => ({ url })) : [],
                      websitPartsRetItems: res.data.websitPartsRetItemList
                    })
                    this.openForm()
                  })
                })
              },
              // 关闭时事件
              closeEvent: () => { }
            })
          }
        },
		confirm: {
			conditions: ({ row, index, column }) => {
			  return row.flag == 'SUBMIT'
			},
		  click: ({ row, index, column }) => {
		    this.$refs.tabPage.addTab({
		      // 对应显示的模块
		      activeKey: "confirm",
		      // 唯一标识
		      key: "confirm",
		      // 页签名称
		      label: "确认",
		      // 打开时事件
		      triggerEvent: () => {
		        this.handleClose()
		        this.$nextTick(() => {
		          this.openType = 3;
		          websitPartsFactoryRetDetail({ id: row.partsRetId }).then(res => {
		            Object.assign(this.formData, res.data, {
		              fileUrl: res.data.fileUrl ? res.data.fileUrl.split(",").map(url => ({ url })) : [],
		              websitPartsRetItems: res.data.websitPartsRetItemList
		            })
		            this.openForm()
		          })
		        })
		      },
		      // 关闭时事件
		      closeEvent: () => { }
		    })
		  }
		},
        // printTp: {
        //   click: ({ row, index, column }) => {

        //   }
        // },
      })
    },
  }
}
</script>

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