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

import { BatteryCharge } from '@vben/icons'
import { useUserStore } from '@vben/stores'

import {
  annualCreditCfg,
  createFormItem,
  firstMonthCreditCfg,
  normalMonthlyCreditCfg,
  referralCreditCfg,
  referralDaysCfg,
  renewalMonthCreditCfg,
} from '#/api/service/common'
import { get } from '#/api/http'
import { schoolService } from '#/api/service/org/school'
import MjTable, {
  mj_form_input,
  mj_form_select,
  mj_form_text,
} from '#/components/mj/mj-table'
import { pattern_phone } from '#/components/mj/mj-table/fmt'
import obj from '#/utils/obj'
import { useSearchSp } from '#/views/sp/hooks/search'

import TransferCoin from './transfer-coin.vue'

const props = defineProps<{
  showAll?: boolean
}>()

const { userInfo } = storeToRefs(useUserStore())
const notSuperAdmin = !userInfo.value.isSuperAdmin
const gridRef = ref()

const spRender = useSearchSp({
  prepare: { gridRef },
})

// 省市区
const provinceOptions = ref<any[]>([])
const cityOptions = ref<any[]>([])
const districtOptions = ref<any[]>([])

async function fetchAreaList(parentId: string) {
  const res = await get<any>('/xkw/area/list', { parentId })
  return (res?.rows || []).map((item: any) => ({
    label: item.name,
    value: item.id,
  }))
}

async function loadProvinces() {
  provinceOptions.value = await fetchAreaList('0')
}

async function onProvinceChange({ data }: any) {
  data.cityId = ''
  data.districtId = ''
  cityOptions.value = []
  districtOptions.value = []
  if (data.provinceId) {
    cityOptions.value = await fetchAreaList(data.provinceId)
  }
}

async function onCityChange({ data }: any) {
  data.districtId = ''
  districtOptions.value = []
  if (data.cityId) {
    districtOptions.value = await fetchAreaList(data.cityId)
  }
}

loadProvinces()

// 调整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,
        },
      },
      notSuperAdmin || {
        required: true,
        field: 'providerName',
        title: '服务商',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: spRender,
          },
        },
      },
      {
        field: 'contact',
        title: '联系人',
        span: 12,
        itemRender: {
          name: mj_form_input,
          events: {
            change: () => {
              adjustItems()
            },
          },
        },
      },
      {
        pattern: pattern_phone,
        field: 'phone',
        title: '联系电话',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'provinceId',
        title: '省份',
        span: 8,
        itemRender: {
          name: mj_form_select,
          props: { clearable: true, placeholder: '请选择省份' },
          options: provinceOptions,
          events: { change: onProvinceChange },
        },
      },
      {
        field: 'cityId',
        title: '城市',
        span: 8,
        itemRender: {
          name: mj_form_select,
          props: { clearable: true, placeholder: '请选择城市' },
          options: cityOptions,
          events: { change: onCityChange },
        },
      },
      {
        field: 'districtId',
        title: '区县',
        span: 8,
        itemRender: {
          name: mj_form_select,
          props: { clearable: true, placeholder: '请选择区县' },
          options: districtOptions,
        },
      },
      createFormItem(firstMonthCreditCfg),
      createFormItem(renewalMonthCreditCfg),
      createFormItem(normalMonthlyCreditCfg),
      createFormItem(annualCreditCfg),
      {
        field: 'enableReferral',
        title: '允许导流',
        span: 12,
        itemRender: {
          name: 'VxeSwitch',
          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',
    'provinceId',
    'cityId',
    'districtId',
    'providerId',
    firstMonthCreditCfg.key,
    renewalMonthCreditCfg.key,
    normalMonthlyCreditCfg.key,
    annualCreditCfg.key,
    'enableReferral',
    referralDaysCfg.key,
    referralCreditCfg.key,
  ],
  beforeEditFormShow(data, edit) {
    if (!edit) {
      data.firstMonthCredit = firstMonthCreditCfg.orgDefault
      data.renewalMonthCredit = renewalMonthCreditCfg.orgDefault
      data.normalMonthlyCredit = normalMonthlyCreditCfg.orgDefault
      data.annualCredit = annualCreditCfg.orgDefault
      data.referralDays = referralDaysCfg.orgDefault
      data.referralCredit = referralCreditCfg.orgDefault
      data.enableReferral = false
      cityOptions.value = []
      districtOptions.value = []
    } else {
      cityOptions.value = []
      districtOptions.value = []
      if (data.provinceId) {
        fetchAreaList(data.provinceId).then((res) => {
          cityOptions.value = res
        })
      }
      if (data.cityId) {
        fetchAreaList(data.cityId).then((res) => {
          districtOptions.value = res
        })
      }
    }
    adjustItems(data)
    calcReferralCredit(data)
    return data
  },
  beforeSaveOrUpdate(data) {
    if (!data.id && userInfo.value.isSpStaff) {
      // 如果是添加，需要补上服务商的id
      data.providerId = userInfo.value.providerId
    }
    return data
  },
} as MjEditFormProps

const searchForm = {
  items: obj.joinObjs(
    notSuperAdmin || {
      title: '服务商',
      field: 'providerId',
      span: 6,
      itemRender: spRender,
    },
  ),
} as MjFormProps

// 表格
const grid = {
  columns: obj.joinObjs<any>(
    { type: 'seq' },
    {
      field: 'name',
      title: '学校',
    },
    { field: 'provinceName', title: '省份' },
    { field: 'cityName', title: '城市' },
    { field: 'districtName', title: '区县' },
    notSuperAdmin || { field: 'providerName', title: '服务商' },
    userInfo.value.isOnlyStaff || {
      field: 'currency',
      title: '乐贝',
      formatter: 'money',
    },
    userInfo.value.isOnlyStaff || {
      field: 'contact',
      title: '联系人',
    },
    userInfo.value.isOnlyStaff || {
      field: 'phone',
      title: '联系电话',
    },
    userInfo.value.isOnlyStaff || {
      fixed: 'right',
      title: '操作',
      slots: { default: 'operation' },
    },
  ),
  beforeLoadData(params) {
    if (!props.showAll && userInfo.value.isSpStaff) {
      params.providerId = userInfo.value.providerId
    }
    return params
  },
} as MjGridProps

// 赠送乐贝
const transferSchool = ref({} as any)
const transferVisible = ref(false)
function transfer(row: any) {
  transferSchool.value = row
  transferVisible.value = true
}
</script>

<template>
  <div class="school-mgr g-container">
    <MjTable
      ref="gridRef"
      :search-form="searchForm"
      :edit-form="editForm"
      :grid="grid"
      :service="schoolService"
      hide-remove
      v-bind="$attrs"
    >
      <template #operation="{ row }">
        <el-button type="success" :icon="BatteryCharge" @click="transfer(row)">
          赠送乐贝
        </el-button>
      </template>
    </MjTable>
    <TransferCoin
      v-model="transferVisible"
      :school="transferSchool"
      @success="gridRef.reload()"
    />
  </div>
</template>

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