<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="750"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑区域经理' : '添加区域经理'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item
        label="区域经理"
        name="managerOwner"
        extra="请绑定区域经理，注意：超管和游客账号不要绑定"
      >
        <OwnerChoose :value="form.userId" @select="onSelect" />
      </a-form-item>
      <a-form-item label="所在地区" name="region">
        <div class="flex-sb">
          <regions-select
            v-model:value="city"
            valueField="label"
            placeholder="请选择省市区"
            class="ele-fluid"
            @change="onChangeRegion"
          />
        </div>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { addManager, updateManager } from '@/api/merchant/manager';
  import { FormInstance, Rule, RuleObject } from 'ant-design-vue/es/form';
  import OwnerChoose from '@/components/UserChoose/index.vue';
  import useFormData from '@/utils/use-form-data';
  import RegionsSelect from '@/components/RegionsSelect/index.vue';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import highlight from '@bytemd/plugin-highlight';

  // // 链接、删除线、复选框、表格等的插件
  import gfm from '@bytemd/plugin-gfm';
  // // 插件的中文语言文件
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  // // 预览界面的样式，这里用的 github 的 markdown 主题
  import 'github-markdown-css/github-markdown-light.css';
  import { Manager } from '@/api/merchant/manager/model';

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Manager | null;
  }>();

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

  const themeStore = useThemeStore();

  // 提交状态
  const loading = ref(false);
  // 已上传数据

  const formRef = ref<FormInstance | null>(null);
  // 编辑器内容，双向绑定
  const content = ref<any>('');
  // 省市区
  const city = ref<string[]>([]);


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

  // 选择地区
  const onChangeRegion = (value) => {
    form.province = value[0];
    form.city = value[1];
    form.area = value[2];
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Manager>({
    managerId: props.data?.managerId,
    userId: props.data?.userId,
    city: props.data?.city,
    area: props.data?.area,
    province: props.data?.province
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    managerName: [
      {
        required: true,
        message: '请输入商户名称',
        type: 'string',
        trigger: 'blur'
      }
    ],

    managerOwner: [
      {
        required: true,
        type: 'number',
        message: '请绑定区域经理',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          console.log(value);
          if (form.userId == 0) {
            return Promise.reject('请绑定区域经理');
          }
          return Promise.resolve();
        }
      }
    ],
    region: [
      {
        required: true,
        type: 'string',
        message: '请选择商户所在区域',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (city.value.length == 0) {
            return Promise.reject('请选择商户所在区域');
          }
          return Promise.resolve();
        }
      }
    ]
  });

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  const onSelect = (item) => {
    form.userId = item.userId;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const managerForm = {
          ...form,
          content: content.value
        };
        const saveOrUpdate = isUpdate.value ? updateManager : addManager;
        saveOrUpdate(managerForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            form.city = '[]';
            resetFields();
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignFields({
            ...props.data
          });
          city.value = [
            `${props.data.province}`,
            `${props.data.city}`,
            `${props.data.area}`
          ];
          isUpdate.value = true;
        } else {
          city.value = [];
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .flex-sb {
    display: flex;
    justify-content: space-between;
  }
</style>
