<template>
  <AFormPanel
    ref="formPanel"
    v-bind="formPanelProps">
    <template #default="formData">
      <div class="form-items">
        <ElFormItem label="图片" prop="picture">
          <Uploader
            ref="uploader"
            :disabled="appUserStore.isXiaoNa"
            v-model:file="formData.picture"/>
        </ElFormItem>
        <ElFormItem v-if="status === 'modify'" label="产品编码" prop="sn">
          <ElInput v-model="formData.sn" :disabled="appUserStore.isXiaoNa" placeholder="产品编码" readonly/>
        </ElFormItem>
        <ElFormItem label="产品分类" prop="goodsCategoryId">
          <GoodsCategorySelect
            :disabled="appUserStore.isXiaoNa"
            v-model="formData.goodsCategoryId"
            :default-biz-type="defaultBizType"
            :default-value="{
              id:formData.goodsCategory?.id,
              categoryName:formData.goodsCategory?.categoryName,
            }"/>
        </ElFormItem>
        <ElFormItem label="产品名称" prop="goodsName">
          <ElInput v-model="formData.goodsName" :disabled="appUserStore.isXiaoNa" placeholder="产品名称"/>
        </ElFormItem>
        <ElFormItem v-if="appUserStore.isXiaoNa" label="计费策略" prop="expenseStrategy">
          <ElRadioGroup v-model="formData.expenseStrategy">
            <ElRadio v-for="it in expenseStrategy" :key="'expenseStrategy'+it.val" :value="it.val" border>{{ it.txt }}</ElRadio>
          </ElRadioGroup>
        </ElFormItem>

        <ElFormItem label="规格" prop="specParams">
          <ElInput v-model="formData.specParams" :disabled="appUserStore.isXiaoNa" placeholder="规格"/>
        </ElFormItem>
        <ElFormItem label="计量单位" prop="unit">
          <ElSelect v-model="formData.unit" :disabled="appUserStore.isXiaoNa">
            <ElOption
              v-for="item in unit"
              :key="'unit'+item.val"
              :label="item.txt"
              :value="item.val"/>
          </ElSelect>
        </ElFormItem>

        <ElFormItem v-if="appUserStore.isXiaoNa&&formData.expenseStrategy !== expenseStrategy.MianFei" label="税率" prop="taxRate">
          <ElInputNumber v-model="formData.taxRate" :max="100" :min="0" :precision="2" :step="0.01" controls-position="right" placeholder="请输入税率">
            <template #suffix>%</template>
          </ElInputNumber>
        </ElFormItem>
        <ElFormItem v-if="appUserStore.isXiaoNa&&formData.expenseStrategy === expenseStrategy.TanXing" label="起步价" prop="initialPrice">
          <ElInputNumber v-model="formData.initialPrice" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入起步价">
            <template #suffix>元/{{ unit.txt(formData.unit) }}</template>
          </ElInputNumber>
        </ElFormItem>
        <ElFormItem v-if="appUserStore.isXiaoNa&&formData.expenseStrategy === expenseStrategy.TanXing" label="起步量" prop="initialQuantity">
          <ElInputNumber v-model="formData.initialQuantity" :min="0" :step="1" controls-position="right" placeholder="请输入起步量">
            <template #suffix>{{ unit.txt(formData.unit) }}</template>
          </ElInputNumber>
        </ElFormItem>
        <ElFormItem
          v-if="appUserStore.isXiaoNa&&formData.expenseStrategy !== expenseStrategy.MianFei"
          :label="formData.expenseStrategy === expenseStrategy.TanXing?'每档单价':(formData.expenseStrategy === expenseStrategy.DanJia?'单价':'价格')"
          prop="unitPrice">
          <ElInputNumber v-model="formData.unitPrice" :min="0" :placeholder="`请输入${formData.expenseStrategy === expenseStrategy.TanXing?'每档单价':(formData.expenseStrategy === expenseStrategy.DanJia?'单价':'价格')}`" :precision="2" :step="1" controls-position="right">
            <template #suffix>{{ (formData.expenseStrategy === expenseStrategy.DanJia || formData.expenseStrategy === expenseStrategy.TanXing ? `元/${unit.txt(formData.unit)}` : `元`) }}</template>
          </ElInputNumber>
        </ElFormItem>
        <ElFormItem v-if="appUserStore.isXiaoNa&&formData.expenseStrategy === expenseStrategy.TanXing" label="每档的量" prop="everyQuantity">
          <ElInputNumber v-model="formData.everyQuantity" :min="0" :step="1" controls-position="right" placeholder="请输入每档的量">
            <template #suffix>{{ unit.txt(formData.unit) }}</template>
          </ElInputNumber>
        </ElFormItem>
        <ElFormItem label="排序" prop="sort">
          <ElInputNumber v-model="formData.sort" :disabled="appUserStore.isXiaoNa" controls-position="right" placeholder="请输入排序"/>
        </ElFormItem>
        <ElFormItem label="是否可用" prop="canuse">
          <el-switch v-model="formData.canuse" :disabled="appUserStore.isXiaoNa"/>
        </ElFormItem>
        <ElFormItem label="备注" prop="memo">
          <ElInput v-model="formData.memo" :disabled="appUserStore.isXiaoNa" placeholder="请输入备注"/>
        </ElFormItem>
      </div>
    </template>
  </AFormPanel>
</template>

<script lang="ts" setup>
import GoodsApi from '@/pages/gds/goods/goods-api.ts'
import Strings from '@/common/utils/strings.ts'
import Uploader from '@/components/uploader/Uploader.vue'
import AFormPanel, {
  type AFormPanelInstance,
  buildFormPanelProps,
} from '@/components/a-form-panel/AFormPanel.tsx'
import {
  expenseStrategy,
  unit,
} from '@/pages/gds/goods/constants.ts'
import { bizType } from '@/pages/gds/goods-category/constants.ts'
import GoodsCategorySelect from '@/pages/gds/goods-category/GoodsCategorySelect.vue'
import { useAppUserStore } from '@/common/app/app-user-store.ts'

const props = withDefaults(defineProps<{
  research?: () => void
  defaultBizType: typeof bizType[number]['val']
}>(), {
  research: () => {
  },
})
const appUserStore = useAppUserStore()
const formPanelIns = useTemplateRef<AFormPanelInstance>('formPanel')
const uploaderIns = useTemplateRef<InstanceType<typeof Uploader>>('uploader')
const status = ref<'add' | 'modify'>('add')
const formPanelProps = buildFormPanelProps<GoodsTypes.GoodsForm>({
  detailsLoader(id?: string) {
    if (Strings.isBlank(id)) {
      status.value = 'add'
      return Promise.resolve({
        expenseStrategy: expenseStrategy.MianFei,
        unit: unit.Dun,
        canuse: true,
        sort: 0,
        taxRate: 0,
        unitPrice: 0,
        initialPrice: 0,
        initialQuantity: 0,
        everyQuantity: 0,
      })
    } else {
      status.value = 'modify'
      return GoodsApi
        .detail(id!)
        .then((res) => {
          if (res.data.picture != null) uploaderIns.value?.setDefaultFiles([ res.data.picture ])
          return {
            id: res.data.id,
            goodsCategoryId: res.data.goodsCategoryId,
            sn: res.data.sn,
            goodsName: res.data.goodsName,
            specParams: res.data.specParams,
            picture: res.data.picture,
            unit: res.data.unit,
            sort: res.data.sort,
            canuse: res.data.canuse,
            memo: res.data.memo,
            expenseStrategy: res.data.expenseItem?.expenseStrategy,
            taxRate: res.data.expenseItem?.taxRate,
            unitPrice: res.data.expenseItem?.unitPrice,
            initialPrice: res.data.expenseItem?.initialPrice,
            initialQuantity: res.data.expenseItem?.initialQuantity,
            everyQuantity: res.data.expenseItem?.everyQuantity,
            goodsCategory: res.data.goodsCategory,
          }
        })
    }
  },
  doSubmit(data) {
    if (status.value === 'add') {
      return GoodsApi.add({
        goodsCategoryId: data.goodsCategoryId,
        goodsName: data.goodsName,
        specParams: data.specParams,
        picture: data.picture,
        unit: data.unit,
        sort: data.sort,
        canuse: data.canuse,
        memo: data.memo,
        expenseStrategy: data.expenseStrategy,
        taxRate: data.taxRate,
        initialPrice: data.initialPrice,
        initialQuantity: data.initialQuantity,
        everyQuantity: data.everyQuantity,
        unitPrice: data.unitPrice,
        expenseItem: {
          expenseItemCategory: 'ChanPin',
          expenseStrategy: data.expenseStrategy,
          unit: data.unit,
          taxRate: data.taxRate,
          unitPrice: data.unitPrice,
          initialPrice: data.initialPrice,
          initialQuantity: data.initialQuantity,
          everyQuantity: data.everyQuantity,
          memo: data.memo,
        },
      })
        .then(props.research)
    } else {
      return GoodsApi.modify({
        id: data.id,
        goodsCategoryId: data.goodsCategoryId,
        goodsName: data.goodsName,
        specParams: data.specParams,
        picture: data.picture,
        unit: data.unit,
        sort: data.sort,
        canuse: data.canuse,
        memo: data.memo,
        expenseStrategy: data.expenseStrategy,
        taxRate: data.taxRate,
        unitPrice: data.unitPrice,
        initialPrice: data.initialPrice,
        initialQuantity: data.initialQuantity,
        everyQuantity: data.everyQuantity,
        expenseItem: {
          expenseItemCategory: 'ChanPin',
          expenseStrategy: data.expenseStrategy,
          unit: data.unit,
          taxRate: data.taxRate,
          unitPrice: data.unitPrice,
          initialPrice: data.initialPrice,
          initialQuantity: data.initialQuantity,
          everyQuantity: data.everyQuantity,
          memo: data.memo,
        },
      })
        .then(props.research)
    }
  },
  watchForm: {
    formItems: [ 'expenseStrategy' ],
  },
  rules: formData => {
    return {
      goodsCategoryId: [ {required: true, message: '请选择产品类型', trigger: 'blur'} ],
      goodsName: [ {required: true, message: '请填写产品名称', trigger: 'blur'} ],
      picture: [ {required: true, message: '请上传图片', trigger: 'blur'} ],
      unit: [ {required: true, message: '请选择计量单位', trigger: 'blur'} ],
      sort: [ {required: true, message: '请填写排序', trigger: 'blur'} ],
      expenseStrategy: [ {required: true, message: '请填选择计费策略', trigger: 'blur'} ],
      taxRate: [ {required: true, message: '请填填写税率', trigger: 'blur'} ],
      unitPrice: [ {required: formData.expenseStrategy !== expenseStrategy.MianFei, message: `请填填写${formData.expenseStrategy === expenseStrategy.TanXing ? '每档单价' : (formData.expenseStrategy === expenseStrategy.DanJia ? '单价' : '价格')}`, trigger: 'blur'} ],
      initialPrice: [ {required: formData.expenseStrategy === expenseStrategy.TanXing, message: '请填写起步价', trigger: 'blur'} ],
      initialQuantity: [ {required: formData.expenseStrategy === expenseStrategy.TanXing, message: '请填写起步量', trigger: 'blur'} ],
      everyQuantity: [ {required: formData.expenseStrategy === expenseStrategy.TanXing, message: '请填写每档的量', trigger: 'blur'} ],
    }
  },
})
watchEffect(() => {
  formPanelProps.title = status.value === 'add' ? '新建产品' : '修改产品'
})
defineExpose({
  open(data?: GoodsTypes.SearchGoodsResult) {
    formPanelIns.value?.open(data?.id)
  },
})
</script>

<style lang="stylus" scoped>
.form-items {
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "picture ." \
  "picture .";

  :deep(.el-form-item) {
    &:first-child {
      align-items: start;
      grid-area: picture
      max-width 300px

      .el-form-item__content {
        justify-content center
      }

      .el-form-item__error {
        width: 100%;
        text-align: center;
      }
    }

    &:last-child:nth-child(2n) {
      grid-column: span 2;
      width: 100%;
    }
  }
}
</style>
