<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-container>
        <div slot="footer" v-if="formType" class="dialog-footer">
          <el-button size="mini" @click="formCancel">取 消</el-button>
          <el-button size="mini" @click="formConfirm" type="primary">确定</el-button>
        </div>
      </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 {
  increOrderSettleList,
  increOrderSettleListExport,
  increOrderSettleDetail,
  increOrderSettleConfirm,
  increOrderSettleRefund
} from '@/api/orderSettleManag.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import formItems from '../mixins/formItems.js'
export default {
  props: {
    storageType: {
      type: String,
      default: ''
    }
  },
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin, formItems],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        selectable: this.selectable
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中数据
      recordSelected: [],
      formTypeName: ['查看', '结算'],
      formType: -1,
      formData: {
        pgIncreItems: []
      },
      formDialog: false,
      defaultSearchData: []
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('bulkSettlemen', {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选订单')
                  return
                }
                increOrderSettleConfirm(this.recordSelected.map(item => item.id)).then(res => {
                  this.$message({ type: 'success', message: `成功!` })
                  this.$refs.pageRef.refreshList()
                })
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return [
        {
          name: '支付状态',
          key: 'payStatus',
          value: this?.$route?.params?.pageCode || '',
          conditions: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '已支付',
              value: 'PAID'
            },
            {
              label: '待支付',
              value: 'WAIT'
            },
            {
              label: '已退款',
              value: 'REFUND'
            },
            {
              label: '过期',
              value: 'EXPIRE'
            },
            {
              label: '取消',
              value: 'CANCEL'
            }
          ]
        }
      ]
    }
  },
  created() {
    if (this.pageCode && !~['PAID', 'WAIT', 'REFUND', 'EXPIRE', 'CANCEL'].indexOf(this.pageCode)) {
      this.defaultSearchData = [{ param: 'a.id', compare: '=', value: this.pageCode, label: '订单单号' }]
    }
  },
  methods: {
    selectable(row, index) {
      return (
        ['PAID'].includes(
          Object.entries(row.selectMapData.payStatus).find(([key, val]) => val == row.payStatus)?.[0]
        ) &&
        ['ING'].includes(
          Object.entries(row.selectMapData.settleStatus).find(([key, val]) => val == row.settleStatus)?.[0]
        )
      )
    },
    // 列表请求函数
    getList(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        if (pam.payStatus) {
          pam.params.push({ param: 'a.pay_status', compare: '=', value: pam.payStatus })
        }
        pam.params.push({ param: 'a.order_channel', compare: '=', value: 'ONLINE' })
        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
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    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
              }
            })
          }
        },
        refund: {
          btnType: 'text',
          prompt: '是否确定退款？',
          conditions: ({ row, index, column }) => {
            return (
              ['PAID'].includes(row.payStatus) &&
              ['ING'].includes(row.settleStatus) &&
              (() => {
                var currentDate = new Date(row.payTime)
                currentDate.setDate(currentDate.getDate() + 7)
                currentDate.setHours(23)
                currentDate.setMinutes(59)
                currentDate.setSeconds(59)
                return currentDate > new Date()
              })()
            )
          },
          click: ({ row, index, column }) => {
            increOrderSettleRefund({ id: row.id }).then(res => {
              this.$message({ type: 'success', message: `退款成功!` })
              this.$refs.pageRef.refreshList()
            })
          }
        },
        settlement: {
          btnType: 'text',
          prompt: '是否确定结算？',
          conditions: ({ row, index, column }) => {
            return ['PAID'].includes(row.payStatus) && ['ING'].includes(row.settleStatus)
          },
          click: ({ row, index, column }) => {
            this.formType = 1
            this.getDetail(row.id)
          }
        }
      })
    },
    getDetail(id) {
      increOrderSettleDetail({ id }).then(res => {
        Object.assign(this.formData, res.data)
        this.openForm()
      })
    },
    openForm() {
      this.formDialog = true
    },
    // 关闭弹窗
    formCancel() {
      this.$refs.formRef.$refs.inlineForm.clearValidate()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          increOrderSettleConfirm([this.formData.id]).then(res => {
            this.$message({ type: 'success', message: `操作成功!` })
            this.formCancel()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    }
  }
}
</script>

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