<template>
  <template-page ref="pageRef" :get-list="getList" :exportList="exportList" :table-attributes="tableAttributes"
    :table-events="tableEvents" :moreParameters="moreParameters" :column-parsing="columnParsing" :operation="operation()"
    :operationColumnWidth="200" :optionsEvensGroup="optionsEvensGroup" :defaultSearchData="defaultSearchData">
    <div class="cartographer">
      <el-dialog :title="formTypeName[formType]" width="100%" :modal="false" :visible.sync="formDialog"
        :before-close="formCancel">
        <zj-form-container v-if="formDialog" ref="formRef" :form-data="formData" :styleSwitch="false">
          <zj-form-module title="基础信息" label-width="120px" :showPackUp="false" :form-data="formData"
            :form-items="formItems">
          </zj-form-module>
          <zj-form-module title="订单信息" label-width="120px" :showPackUp="false" :form-data="formData"
            :form-items="formItemsList">
          </zj-form-module>
          <zj-form-module title="附件图片" label-width="120px" :showPackUp="false" :form-data="formData"
            :form-items="formItemsImgs">
          </zj-form-module>
          <zj-form-module v-if="formType == 1" title="审核信息" label-width="120px" :showPackUp="false" :form-data="formData"
            :form-items="examineInfo">
          </zj-form-module>
        </zj-form-container>
        <div v-if="formType == 1 && formDshType" slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="shenhexinxi">审核</el-button>
        </div>
        <div v-if="formType == 0 && formData.flag == 'OK' && formData.payStatus == 'WAIT' && formData.payType == 1"
          slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="() => { wxPay(formData.id) }">微信支付</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="cartographer">
      <el-dialog title="新增" width="100%" :modal="false" :visible.sync="addFormDialog" :before-close="addFormCancel">
        <zj-form-container v-if="addFormDialog" ref="addFormRef" :form-data="addFormData">
          <zj-form-module v-if="addFormDialog" title="客户信息" label-width="80px" :form-data="addFormData"
            :form-items="basicInfo">
          </zj-form-module>
          <zj-form-module v-if="addFormDialog" title="服务信息" label-width="80px" :form-data="addFormData"
            :form-items="serviceInfo">
          </zj-form-module>
          <zj-form-module v-if="addFormDialog" title="产品信息" label-width="80px" :form-data="addFormData"
            :form-items="productInfo">
          </zj-form-module>
        </zj-form-container>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="formConfirm">提交</el-button>
        </div>
      </el-dialog>
    </div>
    <el-dialog title="微信支付" :visible.sync="isPay" width="50%" :close-on-click-modal="false" :modal-append-to-body="false"
      @close="codeUrl = ''">
      <h3 style="text-align: center;">扫二维码支付</h3>
      <div ref="payQRCode" style="display: flex; justify-content: center;" />
      <div style="color: #EA8000;text-align: center;margin-top: 20px;">注：支付成功后，方可操作！</div>
      <div style="display: flex;justify-content: flex-end;margin-top: 30px;">
        <el-button size="mini" type="text" @click="codeUrl = ''">取消</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { increOrderSettleExamine, increOrderSettleGetBrand, increOrderSettleGeneratePayCode, increOrderSettleList, increOrderSettleListExport, increOrderSettleAdd, increOrderSettleDetail, increOrderSettleConfirm, increOrderSettleRefund } from "@/api/orderSettleManag.js"
import operation_mixin from '@/components/template/operation_mixin.js'
import formItems from "../mixins/formItems.js"
import basicInfo from "../mixins/basicInfo.js"
import serviceInfo from "../mixins/serviceInfo.js"
import productInfo from "../mixins/productInfo.js"
import examineInfo from "../mixins/examineInfo.js"
import QRCode from "qrcodejs2";
export default {
  props: {
    storageType: {
      type: String,
      default: ""
    }
  },
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin, formItems, basicInfo, serviceInfo, productInfo, examineInfo],
  data() {
    return {
      isPay: false,
      codeUrl: "",
      // 表格属性
      tableAttributes: {
      },
      // 表格事件
      tableEvents: {
      },
      // 勾选选中数据
      recordSelected: [],
      formTypeName: ["查看", "审批"],
      formType: -1,
      formData: {
        flagSh: "",
        flag: "",
        examineRemark: "",
        pgIncreItems: []
      },
      formDialog: false,
      addFormDialog: false,
      formDshType: false,
      defaultSearchData: [],
      addFormData: {
        shiyongleixing: "按使用年限",
        "amount": "",
        "brandId": "",
        "brandName": "",
        "buyCertImg": [],
        "commissionAmount": "",
        "companyWechatId": "",
        "companyWechatName": "",
        "createBy": "",
        "createTime": "",
        "examineBy": "",
        "examineRemark": "",
        "examineTime": "",
        "flag": "",
        "id": "",
        "increContent": "",
        "increType": "",
        "insideCode": "",
        "insideCodeImg": [],
        "insureTime": "",
        "invoiceAmount": "",
        "invoiceTime": "",
        "limitNum": "",
        "machineImg": [],
        "mainId": "",
        "mainImg": "",
        "mainName": "",
        "orderChannel": "",
        "payNo": "",
        "payStatus": "",
        "payTime": "",
        "payType": "",
        "pgIncreId": "",
        "pgIncreItemId": "",
        "refundNo": "",
        "refundTime": "",
        "remark": "",
        "residuNum": "",
        "serviceEndTime": "",
        "serviceNo": "",
        "settleRemark": "",
        "settleStatus": "",
        "transcationId": "",
        "updateBy": "",
        "updateTime": "",
        "userAddress": "",
        "userAddressId": "",
        "userMobile": "",
        "userName": "",
        "websitAmount": "",
        "websitId": "",
        "websitName": "",
        "workerAmount": "",
        "workerId": "",
        "workerIdcard": "",
        "workerMobile": "",
        "workerName": "",
        "workerOpenId": ""
      },
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth("add", {
              click: () => {
                this.addFormOpen()
              }
            })
          ],
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return [
        {
          name: '审批状态',
          key: 'flag',
          value: '',
          conditions: [
            {
              label: "全部",
              value: ""
            }, {
              label: "待审核",
              value: "WAIT"
            }, {
              label: "通过",
              value: "OK"
            }, {
              label: "失败",
              value: "FAIL"
            }]
        },
      ]
    },
  },
  watch: {
    codeUrl(newVal) {
      this.isPay = !!newVal
      if (!this.isPay) {
        if (this.wxpayTimeId) {
          clearTimeout(this.wxpayTimeId)
        }
        this.formCancel()
        this.addFormCancel()
        this.$refs?.pageRef?.refreshList()
      }
    }
  },
  created() {
    if (this.pageCode) {
      this.defaultSearchData = [{ "param": "a.id", "compare": "=", "value": this.pageCode, label: "订单单号" }]
    }
  },
  methods: {
    wxPay(id) {
      increOrderSettleGeneratePayCode({ id }).then(res => {
        this.codeUrl = res.data.codeUrl
        if (this.$refs?.payQRCode?.innerHTML) {
          this.$refs.payQRCode.innerHTML = '';
        }
        this.$nextTick(() => {
          new QRCode(this.$refs.payQRCode, {
            text: res.data.codeUrl,
            width: 200,
            height: 200,
            colorDark: "#333333", // 二维码颜色
            colorLight: "#ffffff", // 二维码背景色
            correctLevel: QRCode.CorrectLevel.L // 容错率，L/M/H
          });
          this.wxpaygetDetail(id)
        });
      })
    },
    wxpaygetDetail(id) {
      if (this.wxpayTimeId) {
        clearTimeout(this.wxpayTimeId)
      }
      this.wxpayTimeId = setTimeout(() => {
        increOrderSettleDetail({ id }).then(res => {
          if (res.data.payStatus == "PAID" && res.data.payType == 1) {
            this.codeUrl = ""
            this.addFormCancel()
          } else {
            this.wxpaygetDetail(id)
          }
        })
      }, 1000)
    },
    // 列表请求函数
    getList(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        if (pam.flag) {
          pam.params.push({ "param": "a.flag", "compare": "=", "value": pam.flag })
        }
        pam.params.push({ "param": "a.order_channel", "compare": "=", "value": "SELF" })
        cb && cb(pam)
        return increOrderSettleList(pam)
      } catch (err) {
      }
    },
    // 列表导出函数
    exportList: increOrderSettleListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.jname === 'residuNum') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div style="padding:0 6px;cursor: pointer;">
              {row["increType"] != 1 ? row["residuNum"] : ""}
            </div>
          )
        }
      }
      if (item.jname === 'serviceEndTime') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div style="padding:0 6px;cursor: pointer;">
              {row[column.columnAttributes.prop] ? row[column.columnAttributes.prop].split(" ")[0] : ""}
            </div>
          )
        }
      }
      return defaultData
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        detail: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.formType = 0
            this.getDetail(row.id)
          }
        },
        orderDetail: {
          btnType: 'text',
          conditions: ({ row, index, column }) => {
            return ["PAID", "REFUND"].includes(row.payStatus)
          },
          click: ({ row, index, column }) => {
            this.$router.push({
              name: 'workOrderPool',
              params: {
                pageName: row.id,
                pageType: 'pgIncreItemId',
                pageCode: row.id,
              },
            })
          }
        },
        examine: {
          btnType: 'text',
          conditions: ({ row, index, column }) => {
            return row.flag == "WAIT"
          },
          click: ({ row, index, column }) => {
            this.formType = 1
            this.formDshType = true
            this.getDetail(row.id)
          }
        },
      })
    },
    getDetail(id) {
      increOrderSettleDetail({ id }).then(res => {
        Object.assign(this.formData, res.data)
        this.openForm()
      })
    },
    openForm() {
      this.formDialog = true
    },
    // 关闭弹窗
    formCancel() {
      this.formDshType = false
      this.$refs?.formRef?.$refs?.inlineForm?.clearValidate()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
    },
    openAddForm() {
      this.formDialog = true
    },
    shenhexinxi() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          increOrderSettleExamine({ ...this.formData, flag: this.formData.flagSh }).then(res => {
            this.$message({ type: 'success', message: `审核完成!` })
            this.formCancel()
            this.$refs?.pageRef?.refreshList()
          })
        }
      })
    },
    addFormCancel() {
      this.formDshType = false
      this.$refs?.addFormRef?.$refs?.inlineForm?.clearValidate()
      this.$data.addFormData = this.$options.data().addFormData
      this.addFormDialog = false
    },
    addFormOpen() {
      this.getincreOrderSettleGetBrand()
      this.addFormDialog = true
    },
    formConfirm() {
      this.$refs.addFormRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          increOrderSettleAdd({
            ...this.addFormData,
            "serviceEndTime": this.addFormData.serviceEndTime + " 23:59:59",
            "buyCertImg": this.addFormData.buyCertImg.map(item => item.url).join(","),
            "insideCodeImg": this.addFormData.insideCodeImg.map(item => item.url).join(","),
            "machineImg": this.addFormData.machineImg.map(item => item.url).join(","),
          }).then(res => {
            this.$message({ type: 'success', message: `新增成功!` })
            this.$refs?.pageRef?.refreshList()
            this.addFormCancel()
            // if (res.data.payStatus == "WAIT" && res.data.payType == 1) {
            //   this.wxPay(res.data.id)
            // } else {
            //   this.addFormCancel()
            // }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss">
.redbordererr {
  .el-form-item {
    margin: 0 !important;
    overflow: hidden;
  }
}
</style>
