<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import type { MjEditFormProps, MjGridProps } from '#/components/mj/mj-table'

import {
  annualCreditCfg,
  createFormItem,
  firstMonthCreditCfg,
  normalMonthlyCreditCfg,
  referralCreditCfg,
  referralDaysCfg,
  renewalMonthCreditCfg,
} from '#/api/service/common'
import { spService } from '#/api/service/sp/sp'
import MjTable, {
  mj_form_input,
  mj_form_money,
  mj_form_switch,
  mj_form_text,
} from '#/components/mj/mj-table'
import { pattern_phone } from '#/components/mj/mj-table/fmt'
import obj from '#/utils/obj'

// 调整item
const adjustItems = (data?: any) => {
  data = data || gridRef.value.getEditFormData()
  const fields = [referralDaysCfg.key, referralCreditCfg.key]
  if (data.enableReferral) {
    gridRef.value.showEditFormItems(fields)
  } else {
    gridRef.value.hideEditFormItems(fields)
  }
}

// 计算referralCredit
const calcReferralCredit = (data: any) => {
  const days = Number(data.referralDays) || 0
  data.referralCredit = days ? days * 50 : ''
}

// 表单
const editForm = {
  modal: {
    width: 900,
  },
  form: {
    titleWidth: 100,
    items: [
      {
        required: true,
        field: 'name',
        title: '名称',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'contact',
        title: '联系人',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        pattern: pattern_phone,
        field: 'phone',
        title: '联系电话',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'remark',
        title: '备注',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'sellerFlag',
        title: '乐贝卖家',
        span: 12,
        itemRender: {
          name: mj_form_switch,
        },
      },
      {
        field: 'buyerFlag',
        title: '乐贝买家',
        span: 12,
        itemRender: {
          name: mj_form_switch,
        },
      },
      {
        field: 'publicOrgFlag',
        title: '公益组织',
        span: 12,
        itemRender: {
          name: mj_form_switch,
        },
      },
      {
        field: 'limitCurrency',
        title: '乐贝限额',
        span: 12,
        itemRender: {
          name: mj_form_money,
          props: { clearable: true, showPrefix: false },
        },
      },
      createFormItem(firstMonthCreditCfg),
      createFormItem(renewalMonthCreditCfg),
      createFormItem(normalMonthlyCreditCfg),
      createFormItem(annualCreditCfg),
      {
        field: 'enableReferral',
        title: '允许导流',
        span: 12,
        itemRender: {
          name: mj_form_switch,
          events: {
            change: () => {
              adjustItems()
            },
          },
        },
      },
      createFormItem(referralDaysCfg, {
        itemRender: {
          name: mj_form_input,
          events: {
            change: ({ data }: any) => {
              calcReferralCredit(data)
            },
          },
        },
      }),
      createFormItem(referralCreditCfg, {
        itemRender: {
          name: mj_form_text,
        },
      }),
    ],
    data: {},
  },
  updateFields: [
    'id',
    'name',
    'contact',
    'phone',
    'limitCurrency',
    'sellerFlag',
    'buyerFlag',
    'publicOrgFlag',
    firstMonthCreditCfg.key,
    renewalMonthCreditCfg.key,
    normalMonthlyCreditCfg.key,
    annualCreditCfg.key,
    'enableReferral',
    referralDaysCfg.key,
    referralCreditCfg.key,
  ],
  beforeEditFormShow(data, edit) {
    if (!edit) {
      data.firstMonthCredit = firstMonthCreditCfg.spDefault
      data.renewalMonthCredit = renewalMonthCreditCfg.spDefault
      data.normalMonthlyCredit = normalMonthlyCreditCfg.spDefault
      data.annualCredit = annualCreditCfg.spDefault
      data.referralDays = referralDaysCfg.spDefault
      data.referralCredit = referralCreditCfg.spDefault
      data.enableReferral = false
    }
    adjustItems(data)
    calcReferralCredit(data)
    return data
  },
} as MjEditFormProps

// 表格
const gridRef = ref()
const grid = {
  columns: obj.joinObjs<any>(
    { type: 'seq' },
    {
      field: 'name',
      title: '名称',
    },
    { field: 'currency', title: '乐贝', formatter: 'money' },
    { field: 'learnAmount', title: '乐学金', formatter: 'money' },
    {
      title: '卖家',
      slots: {
        default: 'sellerFlag',
      },
    },
    { field: 'lockCurrency', title: '冻结乐贝', formatter: 'money' },
    { field: 'limitCurrency', title: '乐贝卖出限额', formatter: 'money' },
    { field: 'soldCurrency', title: '累计已售乐贝', formatter: 'money' },
    {
      title: '买家',
      slots: {
        default: 'buyerFlag',
      },
    },
    {
      title: '公益组织',
      slots: {
        default: 'publicOrgFlag',
      },
    },
    {
      title: '联系人',
      formatter: (row: any) => `${row.contact || ''}/${row.phone || ''}`,
    },
    { field: 'remark', title: '备注' },
  ),
} as MjGridProps

function sellerFlagChange(row: any) {
  const oldFlag = !row.sellerFlag

  spService
    .saveOrUpdate({
      id: row.id,
      sellerFlag: row.sellerFlag,
    })
    .catch(() => {
      row.sellerFlag = oldFlag
    })
}

function publicOrgFlagChange(row: any) {
  const oldFlag = !row.publicOrgFlag

  spService
    .saveOrUpdate({
      id: row.id,
      publicOrgFlag: row.publicOrgFlag,
    })
    .catch(() => {
      row.publicOrgFlag = oldFlag
    })
}

function buyerFlagChange(row: any) {
  const oldFlag = !row.buyerFlag

  spService
    .saveOrUpdate({
      id: row.id,
      buyerFlag: row.buyerFlag,
    })
    .catch(() => {
      row.buyerFlag = oldFlag
    })
}
</script>

<template>
  <div class="sp-mgr g-container">
    <MjTable
      ref="gridRef"
      :edit-form="editForm"
      :grid="grid"
      hide-remove
      :service="spService"
      v-bind="$attrs"
    >
      <template #sellerFlag="{ row }">
        <el-switch v-model="row.sellerFlag" @click="sellerFlagChange(row)" />
      </template>
      <template #buyerFlag="{ row }">
        <el-switch v-model="row.buyerFlag" @click="buyerFlagChange(row)" />
      </template>
      <template #publicOrgFlag="{ row }">
        <el-switch
          v-model="row.publicOrgFlag"
          @click="publicOrgFlagChange(row)"
        />
      </template>
    </MjTable>
  </div>
</template>

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