<template>
  <div class="card">
    <Card :bordered="false" class="card">
      <BasicForm @register="registerForm">
        <template #qrcode>
          <ContentUploadText>
            <template #uploadImg>
              <CustomUploadComp :imgUrl="qrcodePic" @setImg="handleSetCodeImgUrl" />
            </template>
            <template #uploadText>
              <div class="box-outline"> 支持.PNG、.JPG格式，建议尺寸为300*300px，大小不超过5M </div>
            </template>
          </ContentUploadText>
        </template>
        <template #customProv>
          <BasicForm @register="registerCustomForm" />
        </template>
      </BasicForm>
    </Card>
    <Loading v-bind="compState" />
    <Authority value="api:yt:enterprise:update:update">
      <a-button
        v-if="isWhereAdmin !== 'CUSTOMER_USER'"
        @click="handleUpdateInfo"
        type="primary"
        class="mt-4"
        >更新基本信息</a-button
      >
    </Authority>
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref, computed } from 'vue';
  import { Card } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { schemas, provSchemas } from '../config/enterPriseInfo.config';
  import { getAreaList, getEnterPriseDetail, updateEnterPriseDetail } from '/@/api/oem/index';
  import { Loading } from '/@/components/Loading';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { createLocalStorage } from '/@/utils/cache';
  import type { CityItem, Code } from '../types';
  import { Authority } from '/@/components/Authority';
  import { USER_INFO_KEY } from '/@/enums/cacheEnum';
  import { getAuthCache } from '/@/utils/auth';
  import ContentUploadText from './ContentUploadText.vue';
  import { CustomUploadComp } from './customUplaod/index';

  export default defineComponent({
    components: {
      Card,
      BasicForm,
      Loading,
      Authority,
      ContentUploadText,
      CustomUploadComp,
    },
    setup() {
      const userInfo: any = getAuthCache(USER_INFO_KEY);
      const isWhereAdmin: any = computed(() => {
        if (userInfo.roles.includes('TENANT_ADMIN')) {
          return 'TENANT_ADMIN';
        } else if (userInfo.roles.includes('CUSTOMER_USER')) {
          return 'CUSTOMER_USER';
        } else {
          return 'SYS_ADMIN';
        }
      });

      const loading = ref(false);
      const compState = ref({
        absolute: false,
        loading: false,
        tip: '拼命加载中...',
      });
      const [registerForm, { getFieldsValue, setFieldsValue, validate, clearValidate }] = useForm({
        labelWidth: 80,
        schemas,
        showResetButton: false,
        showSubmitButton: false,
        wrapperCol: {
          span: 12,
        },
      });

      const [
        registerCustomForm,
        { getFieldsValue: getNameTown, updateSchema, setFieldsValue: setNameTown },
      ] = useForm({
        labelWidth: 80,
        schemas: provSchemas,
        showResetButton: false,
        showSubmitButton: false,
        compact: true,
        actionColOptions: {
          span: 0,
        },
      });

      const { createMessage } = useMessage();

      const qrcodePic = ref();
      const handleSetCodeImgUrl = (d) => {
        qrcodePic.value = d;
      };
      // 更新
      const handleUpdateInfo = async () => {
        try {
          const fieldsValue = getFieldsValue();
          const { nameTown } = getNameTown();
          const newFieldValue: any = {
            ...fieldsValue,
            codeTown: nameTown,
            qrCode: qrcodePic.value,
          };
          delete newFieldValue.nameProv;
          delete newFieldValue.nameCity;
          delete newFieldValue.nameCoun;
          delete newFieldValue.nameTown;
          // 表单校验
          let validateArray = [
            'name',
            'abbreviation',
            'officialWebsite',
            'email',
            'synopsis',
            'nameCountry',
            'address',
            'contacts',
            'tel',
            'id',
          ];
          if (newFieldValue.qrCode == undefined || newFieldValue.qrCode == '') {
            validateArray.push('qrcode');
          } else {
            const findExistIndex = validateArray.findIndex((o) => o == 'qrcode');
            if (findExistIndex !== -1) {
              validateArray.splice(findExistIndex, 1);
            }
          }
          if (newFieldValue.codeTown == undefined) {
            validateArray.push('prov');
            console.log(validateArray);
          } else {
            const findExistIndex1 = validateArray.findIndex((o) => o == 'prov');
            if (findExistIndex1 !== -1) {
              validateArray.splice(findExistIndex1, 1);
            }
            clearValidate('prov');
          }
          const values = await validate(validateArray);
          if (!values) return;
          compState.value.loading = true;
          await updateEnterPriseDetail(newFieldValue);
          createMessage.success('更新信息成功');
          setEnterPriseInfo(newFieldValue);
        } finally {
          compState.value.loading = false;
        }
      };

      const userStore = useUserStore();
      const storage = createLocalStorage();

      // 设置企业信息
      function setEnterPriseInfo(newFieldValue) {
        // 保存store
        userStore.setEnterPriseInfo(newFieldValue);
        // 保存本地缓存
        storage.set('enterpriseInfo', newFieldValue);
      }

      // 地区显示回显和数据联动
      async function updateCityData(
        cities: CityItem[],
        couns: CityItem[],
        towns: CityItem[],
        code: Code
      ) {
        // 加工后端返回字段

        cities.forEach((item) => {
          item.label = item.name;
          item.value = item.code;
        });

        couns.forEach((item) => {
          item.label = item.name;
          item.value = item.code;
        });
        towns.forEach((item) => {
          item.label = item.name;
          item.value = item.code;
        });
        const { codeProv, codeCity, codeCoun, codeTown } = code;
        updateSchema([
          {
            field: 'nameCity',
            componentProps: ({ formModel }) => {
              return {
                options: cities,
                async onChange(value) {
                  if (value === undefined) {
                    formModel.nameCoun = undefined; //  reset city value
                    formModel.nameTown = undefined;
                    updateSchema([
                      {
                        field: 'nameCoun',
                        componentProps: {
                          options: [],
                        },
                      },
                      {
                        field: 'nameTown',
                        componentProps: {
                          options: [],
                        },
                      },
                    ]);
                  } else {
                    let couns: CityItem[] = await getAreaList({ parentId: value });
                    couns.forEach((item) => {
                      item.label = item.name;
                      item.value = item.code;
                    });
                    formModel.nameCoun = undefined; //  reset city value
                    formModel.nameTown = undefined;
                    updateSchema({
                      field: 'nameCoun',
                      componentProps: {
                        // 请选择区
                        options: couns,
                        async onChange(value) {
                          if (value === undefined) {
                            formModel.nameTown = undefined;
                          } else {
                            let towns: CityItem[] = await getAreaList({ parentId: value });
                            towns.forEach((item) => {
                              item.label = item.name;
                              item.value = item.code;
                            });
                            formModel.nameTown = undefined;
                            updateSchema({
                              field: 'nameTown',
                              componentProps: {
                                placeholder: '城镇/街道',
                                options: towns,
                              },
                            });
                          }
                        },
                      },
                    });
                  }
                },
              };
            },
          },
          {
            field: 'nameCoun',
            componentProps: {
              options: couns,
              async onChange(value) {
                if (value === undefined) {
                  setNameTown({
                    nameTown: undefined,
                  });
                  updateSchema({
                    field: 'nameTown',
                    componentProps: {
                      placeholder: '城镇/街道',
                      options: [],
                    },
                  });
                } else {
                  let towns = await getAreaList({ parentId: value });
                  towns.forEach((item) => {
                    item.label = item.name;
                    item.value = item.code;
                  });
                  setNameTown({
                    nameTown: undefined,
                  });
                  updateSchema({
                    field: 'nameTown',
                    componentProps: {
                      placeholder: '城镇/街道',
                      options: towns,
                    },
                  });
                }
              },
            },
          },
          {
            field: 'nameTown',
            componentProps: {
              options: towns,
            },
          },
        ]);
        setNameTown({
          nameProv: codeProv,
          nameCity: codeCity,
          nameCoun: codeCoun,
          nameTown: codeTown,
        });
      }

      onMounted(async () => {
        const res = await getEnterPriseDetail();
        if (res.sysTown) {
          const { cities, couns, towns, codeCountry, codeProv, codeCity, codeCoun, codeTown } =
            res.sysTown;
          const code = {
            codeCountry,
            codeProv,
            codeCity,
            codeCoun,
            codeTown,
          };
          updateCityData(cities, couns, towns, code);
          setFieldsValue({ nameCountry: codeCountry });
        }
        setFieldsValue(res);
        qrcodePic.value = res.qrCode;
      });

      return {
        registerForm,
        compState,
        qrcodePic,
        handleUpdateInfo,
        registerCustomForm,
        loading,
        isWhereAdmin,
        handleSetCodeImgUrl,
      };
    },
  });
</script>

<style lang="less" scoped>
  .box-outline {
    border: 1px dashed #d9d9d9;
  }

  .fill-img {
    width: 100%;
    height: 100%;
  }
</style>
