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

import { propService } from '#/api/service/mall/prop'
import MjTable, {
  mj_form_date_range,
  mj_form_image,
  mj_form_input,
  mj_form_money,
  mj_form_select,
  mj_form_switch,
  mj_form_textarea,
} from '#/components/mj/mj-table'
import { pattern_pos_int } from '#/components/mj/mj-table/fmt'
import obj from '#/utils/obj'

const gridRef = ref()

const daySeconds = 24 * 60 * 60

// 时间类型
const prop_type_permanent = 1
const prop_type_range = 2
const prop_type_duration = 3
const propTypeMap = {
  [prop_type_permanent]: '永久有效',
  [prop_type_range]: '范围有效',
  [prop_type_duration]: '时长有效',
} as any
const propTypeOptions = obj.map2options(propTypeMap)

// 调整item
const adjustItems = (data?: any) => {
  data = data || gridRef.value.getEditFormData()
  const type = Number(data.propType)
  if (type === prop_type_range) {
    gridRef.value.hideEditFormItems(['validTime'])
    gridRef.value.showEditFormItems(['range'])
  } else if (type === prop_type_duration) {
    gridRef.value.showEditFormItems(['validTime'])
    gridRef.value.hideEditFormItems(['range'])
  } else {
    gridRef.value.hideEditFormItems(['range', 'validTime'])
  }
}

// 表单
const editForm = {
  modal: {
    width: 720,
  },
  form: {
    titleWidth: 100,
    items: [
      {
        required: true,
        field: 'propName',
        title: '名称',
        span: 24,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        required: true,
        pattern: pattern_pos_int,
        field: 'price',
        title: '价格',
        span: 12,
        itemRender: {
          name: mj_form_money,
          props: {
            showPrefix: false,
          },
        },
      },
      {
        required: true,
        field: 'propCode',
        title: '编码',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        required: true,
        pattern: String.raw`^\d+$`,
        field: 'stock',
        title: '库存',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'status',
        title: '上架',
        span: 12,
        itemRender: {
          name: mj_form_switch,
        },
      },
      {
        required: true,
        field: 'propType',
        title: '时间类型',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: propTypeOptions,
          events: {
            change: (params: any) => {
              adjustItems(params.data)
            },
          },
        },
      },
      {
        required: true,
        pattern: pattern_pos_int,
        field: 'validTime',
        title: '有效天数',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        required: true,
        field: 'range',
        title: '时间范围',
        span: 24,
        itemRender: {
          name: mj_form_date_range,
          props: {
            type: 'datetime',
          },
        },
      },
      {
        required: true,
        field: 'file',
        title: '图片',
        span: 24,
        itemRender: {
          name: mj_form_image,
        },
      },
      {
        field: 'useType',
        title: '用途',
        span: 24,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'propDesc',
        title: '描述',
        span: 24,
        itemRender: {
          name: mj_form_textarea,
          props: { clearable: true, autosize: { minRows: 2, maxRows: 6 } },
        },
      },
    ],
    data: {},
  },
  updateFields: [
    'id',
    'file',
    'stock',
    'propType',
    'startTime',
    'endTime',
    'validTime',
    'propName',
    'status',
    'propCode',
    'price',
    'propDesc',
    'useType',
  ],
  beforeSaveOrUpdate(data) {
    data.file = data.file?.file || undefined
    // 有效时长
    if (data.validTime) {
      data.validTime = Number(data.validTime) * daySeconds
    }
    // 时间范围
    if (data.range) {
      const times = data.range.split(',')
      data.startTime = times[0]
      data.endTime = times[1]
    }
    return data
  },
  beforeEditFormShow(data, edit) {
    if (edit) {
      // 处理头像
      data.file = data.propIcon
        ? {
            url: data.propIcon,
          }
        : undefined
      // 有效时长
      data.validTime = data.validTime
        ? Number(data.validTime) / daySeconds
        : undefined
      // 时间范围
      if (data.startTime && data.endTime) {
        data.range = `${data.startTime},${data.endTime}`
      }
    }
    adjustItems(data)
    return data
  },
} as MjEditFormProps

// 搜索表单
const searchForm = {
  items: [],
} as MjFormProps

// 表格
const grid = {
  columns: [
    { type: 'seq' },
    {
      field: 'propName',
      title: '名称',
    },
    {
      field: 'price',
      title: '价格（乐贝）',
    },
    {
      title: '上架',
      field: 'status',
      slots: {
        default: 'status',
      },
    },
    {
      title: '图片',
      slots: {
        default: 'propIcon',
      },
    },
    {
      field: 'stock',
      title: '库存',
    },
    {
      field: 'propDesc',
      title: '描述',
    },
    {
      field: 'useType',
      title: '用途',
    },
    {
      field: 'propCode',
      title: '标识',
    },
    {
      field: 'propType',
      title: '时间类型',
      formatter: ({ cellValue }) => {
        return propTypeMap[cellValue]
      },
    },
    {
      field: 'startTime',
      title: '开始时间',
    },
    {
      field: 'endTime',
      title: '结束时间',
    },
    {
      field: 'validTime',
      title: '有效时长',
      formatter: ({ cellValue }) => {
        return cellValue ? `${cellValue / daySeconds}天` : ''
      },
    },
  ],
} as MjGridProps

// 状态改变
const statusChange = async (row: any) => {
  const oldFlag = !row.status
  propService
    .changeStatus({
      id: row.id,
      status: row.status,
    })
    .catch(() => {
      row.status = oldFlag
    })
}
</script>

<template>
  <div class="prop-mgr g-container">
    <MjTable
      ref="gridRef"
      :search-form="searchForm"
      :edit-form="editForm"
      :grid="grid"
      hide-remove
      :service="propService"
    >
      <template #status="{ row }">
        <el-switch v-model="row.status" @click="statusChange(row)" />
      </template>
      <template #propIcon="{ row }">
        <div v-if="row.propIcon" class="icon">
          <img :src="row.propIcon" />
        </div>
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped>
.prop-mgr {
  .icon {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 50px;
      height: auto;
    }
  }
}
</style>
