<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑商户入驻申请' : '新增商户入驻申请'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="基本信息">
          <a-form-item label="商户名称" name="merchantName">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入商户名称"
              v-model:value="form.merchantName"
            />
          </a-form-item>

          <a-form-item label="证件号码" name="merchantCode">
            <a-input
              allow-clear
              :maxlength="50"
              placeholder="请输入证件号码"
              v-model:value="form.merchantCode"
            />
          </a-form-item>

          <a-form-item label="商户图标" name="image">
            <div class="flex items-center">
              <a-image
                v-if="form.image"
                :src="form.image"
                :width="80"
                :height="80"
                style="margin-right: 10px"
              />
              <SelectFile
                :placeholder="`请选择图片`"
                :limit="1"
                :data="images"
                @done="chooseImage"
                @del="onDeleteImage"
              />
            </div>
          </a-form-item>

          <a-form-item
            label="商户手机号"
            name="phone"
            extra="手机号码将用做于商户端的登录账号请填写真实手机号码"
          >
            <a-input
              allow-clear
              :maxlength="11"
              placeholder="请输入商户手机号"
              v-model:value="form.phone"
            />
          </a-form-item>

          <a-form-item label="商户姓名" name="realName">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入商户姓名"
              v-model:value="form.realName"
            />
          </a-form-item>

          <a-form-item label="身份证号码" name="idCard">
            <a-input
              allow-clear
              :maxlength="18"
              placeholder="请输入身份证号码"
              v-model:value="form.idCard"
            />
          </a-form-item>

          <a-form-item label="店铺类型" name="shopType">
            <a-input
              allow-clear
              :maxlength="50"
              placeholder="请输入店铺类型"
              v-model:value="form.shopType"
            />
          </a-form-item>

          <a-form-item label="商户分类" name="category">
            <a-input
              allow-clear
              :maxlength="100"
              placeholder="请输入商户分类"
              v-model:value="form.category"
            />
          </a-form-item>
        </a-tab-pane>

        <a-tab-pane key="2" tab="资质信息">
          <a-form-item label="营业执照" name="yyzz">
            <div class="flex items-center">
              <a-image
                v-if="form.yyzz"
                :src="form.yyzz"
                :width="80"
                :height="80"
                style="margin-right: 10px"
              />
              <SelectFile
                :placeholder="`请选择营业执照`"
                :limit="1"
                :data="yyzzImages"
                @done="chooseYyzzImage"
                @del="onDeleteYyzzImage"
              />
            </div>
          </a-form-item>

          <a-form-item label="身份证正面" name="sfz1">
            <div class="flex items-center">
              <a-image
                v-if="form.sfz1"
                :src="form.sfz1"
                :width="80"
                :height="80"
                style="margin-right: 10px"
              />
              <SelectFile
                :placeholder="`请选择身份证正面`"
                :limit="1"
                :data="sfz1Images"
                @done="chooseSfz1Image"
                @del="onDeleteSfz1Image"
              />
            </div>
          </a-form-item>

          <a-form-item label="身份证反面" name="sfz2">
            <div class="flex items-center">
              <a-image
                v-if="form.sfz2"
                :src="form.sfz2"
                :width="80"
                :height="80"
                style="margin-right: 10px"
              />
              <SelectFile
                :placeholder="`请选择身份证反面`"
                :limit="1"
                :data="sfz2Images"
                @done="chooseSfz2Image"
                @del="onDeleteSfz2Image"
              />
            </div>
          </a-form-item>

          <a-form-item label="资质图片" name="files">
            <SelectFile
              :placeholder="`请选择资质图片`"
              :limit="9"
              :data="files"
              @done="chooseFiles"
              @del="onDeleteFiles"
            />
          </a-form-item>
        </a-tab-pane>

        <a-tab-pane key="3" tab="其他信息">
          <a-form-item label="手续费(%)" name="commission">
            <a-input-number
              :step="0.1"
              :max="100"
              :min="0"
              :precision="2"
              class="ele-fluid"
              placeholder="请输入手续费"
              v-model:value="form.commission"
            />
          </a-form-item>

          <a-form-item label="关键字" name="keywords">
            <a-select
              v-model:value="form.keywords"
              mode="tags"
              placeholder="输入关键词后回车"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="是否自营" name="ownStore">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :checked="form.ownStore === 1"
              @update:checked="updateOwnStore"
            />
          </a-form-item>

          <a-form-item label="是否推荐" name="recommend">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :checked="form.recommend === 1"
              @update:checked="updateRecommend"
            />
          </a-form-item>

          <a-form-item label="是否需要审核" name="goodsReview">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :checked="form.goodsReview === 1"
              @update:checked="updateGoodsReview"
            />
          </a-form-item>

          <a-form-item label="状态" name="status">
            <a-radio-group v-model:value="form.status">
              <a-radio :value="0">待审核</a-radio>
              <a-radio :value="1">审核通过</a-radio>
              <a-radio :value="2">审核驳回</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="驳回原因" name="reason" v-if="form.status === 2">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入驳回原因"
              v-model:value="form.reason"
            />
          </a-form-item>

          <a-form-item label="备注" name="comments">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入备注"
              v-model:value="form.comments"
            />
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import {
    addShopMerchantApply,
    updateShopMerchantApply
  } from '@/api/shop/shopMerchantApply';
  import { ShopMerchantApply } from '@/api/shop/shopMerchantApply/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ShopMerchantApply | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const activeKey = ref('1');

  // 图片数据
  const images = ref<ItemType[]>([]);
  const yyzzImages = ref<ItemType[]>([]);
  const sfz1Images = ref<ItemType[]>([]);
  const sfz2Images = ref<ItemType[]>([]);
  const files = ref<ItemType[]>([]);

  // 表单数据
  const form = reactive<ShopMerchantApply>({
    applyId: undefined,
    type: 1,
    merchantName: undefined,
    merchantCode: undefined,
    image: undefined,
    phone: undefined,
    realName: undefined,
    idCard: undefined,
    shopType: undefined,
    category: undefined,
    commission: undefined,
    keywords: undefined,
    yyzz: undefined,
    sfz1: undefined,
    sfz2: undefined,
    files: undefined,
    userId: undefined,
    ownStore: 0,
    recommend: 0,
    goodsReview: 1,
    name2: undefined,
    reason: undefined,
    comments: undefined,
    status: 0,
    sortNumber: 100,
    tenantId: undefined
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    merchantName: [
      {
        required: true,
        type: 'string',
        message: '请输入商户名称',
        trigger: 'blur'
      }
    ],
    merchantCode: [
      {
        required: true,
        type: 'string',
        message: '请输入证件号码',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        type: 'string',
        message: '请输入商户姓名',
        trigger: 'blur'
      }
    ],
    idCard: [
      {
        required: true,
        type: 'string',
        message: '请输入身份证号码',
        trigger: 'blur'
      }
    ],
    shopType: [
      {
        required: true,
        type: 'string',
        message: '请输入店铺类型',
        trigger: 'blur'
      }
    ],
    category: [
      {
        required: true,
        type: 'string',
        message: '请输入商户分类',
        trigger: 'blur'
      }
    ],
    yyzz: [
      {
        required: true,
        message: '请上传营业执照',
        trigger: 'change'
      }
    ],
    sfz1: [
      {
        required: true,
        message: '请上传身份证正面',
        trigger: 'change'
      }
    ],
    sfz2: [
      {
        required: true,
        message: '请上传身份证反面',
        trigger: 'change'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }

    formRef.value
      .validate()
      .then(() => {
        loading.value = true;

        // 处理关键字数组转字符串
        let keywordsStr = '';
        if (Array.isArray(form.keywords)) {
          keywordsStr = JSON.stringify(form.keywords);
        } else if (typeof form.keywords === 'string') {
          try {
            JSON.parse(form.keywords);
            keywordsStr = form.keywords;
          } catch {
            keywordsStr = JSON.stringify([form.keywords]);
          }
        }

        const formData = {
          ...form,
          keywords: keywordsStr,
          files:
            files.value.length > 0
              ? JSON.stringify(files.value.map((item) => item.url))
              : undefined
        };

        const saveOrUpdate = isUpdate.value
          ? updateShopMerchantApply
          : addShopMerchantApply;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 图片选择处理
  const chooseImage = (data: FileRecord) => {
    images.value = [
      {
        uid: data.id,
        url: data.path,
        status: 'done'
      }
    ];
    form.image = data.path;
  };

  const onDeleteImage = () => {
    images.value = [];
    form.image = undefined;
  };

  const chooseYyzzImage = (data: FileRecord) => {
    yyzzImages.value = [
      {
        uid: data.id,
        url: data.path,
        status: 'done'
      }
    ];
    form.yyzz = data.path;
  };

  const onDeleteYyzzImage = () => {
    yyzzImages.value = [];
    form.yyzz = undefined;
  };

  const chooseSfz1Image = (data: FileRecord) => {
    sfz1Images.value = [
      {
        uid: data.id,
        url: data.path,
        status: 'done'
      }
    ];
    form.sfz1 = data.path;
  };

  const onDeleteSfz1Image = () => {
    sfz1Images.value = [];
    form.sfz1 = undefined;
  };

  const chooseSfz2Image = (data: FileRecord) => {
    sfz2Images.value = [
      {
        uid: data.id,
        url: data.path,
        status: 'done'
      }
    ];
    form.sfz2 = data.path;
  };

  const onDeleteSfz2Image = () => {
    sfz2Images.value = [];
    form.sfz2 = undefined;
  };

  const chooseFiles = (data: FileRecord) => {
    files.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
  };

  const onDeleteFiles = (index: number) => {
    files.value.splice(index, 1);
  };

  // Switch开关处理
  const updateOwnStore = (value: boolean) => {
    form.ownStore = value ? 1 : 0;
  };

  const updateRecommend = (value: boolean) => {
    form.recommend = value ? 1 : 0;
  };

  const updateGoodsReview = (value: boolean) => {
    form.goodsReview = value ? 1 : 0;
  };

  const { resetFields } = useForm(form, rules);

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        yyzzImages.value = [];
        sfz1Images.value = [];
        sfz2Images.value = [];
        files.value = [];

        if (props.data) {
          isUpdate.value = true;
          assignObject(form, props.data);

          // 处理图片回显
          if (props.data.image) {
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            });
          }

          if (props.data.yyzz) {
            yyzzImages.value.push({
              uid: uuid(),
              url: props.data.yyzz,
              status: 'done'
            });
          }

          if (props.data.sfz1) {
            sfz1Images.value.push({
              uid: uuid(),
              url: props.data.sfz1,
              status: 'done'
            });
          }

          if (props.data.sfz2) {
            sfz2Images.value.push({
              uid: uuid(),
              url: props.data.sfz2,
              status: 'done'
            });
          }

          // 处理关键字回显
          if (props.data.keywords) {
            try {
              form.keywords = JSON.parse(props.data.keywords);
            } catch {
              form.keywords = [props.data.keywords];
            }
          }

          // 处理资质图片回显
          if (props.data.files) {
            try {
              const fileUrls = JSON.parse(props.data.files);
              if (Array.isArray(fileUrls)) {
                fileUrls.forEach((url) => {
                  files.value.push({
                    uid: uuid(),
                    url: url,
                    status: 'done'
                  });
                });
              }
            } catch {
              // 如果解析失败，当作单个URL处理
              files.value.push({
                uid: uuid(),
                url: props.data.files,
                status: 'done'
              });
            }
          }
        } else {
          isUpdate.value = false;
          // 设置默认值
          form.ownStore = 0;
          form.recommend = 0;
          form.goodsReview = 1;
          form.status = 0;
          form.sortNumber = 100;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .ele-fluid {
    width: 100%;
  }
</style>
