<template>
  <div class="card">
    <Card :bordered="false" class="card">
      <BasicForm @register="registerForm">
        <template #qrcode>
          <Upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="customUploadqrcodePic"
            :before-upload="beforeUploadqrcodePic"
          >
            <img v-if="qrcodePic" :src="qrcodePic" alt="avatar" />
            <div v-else>
              <div style="margin-top: 1.875rem">
                <LoadingOutlined v-if="loading" />
                <PlusOutlined v-else style="font-size: 2.5rem" />
              </div>
              <div
                class="ant-upload-text flex"
                style="width: 180px; height: 100px; align-items: center; font-size: 0.5625rem"
              >
                支持.PNG、.JPG格式，建议尺寸为300*300px，大小不超过2M</div
              >
            </div>
          </Upload>
        </template>
        <template #customProv>
          <BasicForm @register="registerCustomForm" />
        </template>
      </BasicForm>
    </Card>
    <Loading v-bind="compState" />
    <Authority value="api:yt:enterprise:update:put">
      <a-button @click="handleUpdateInfo" type="primary" class="mt-4">更新基本信息</a-button>
    </Authority>
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { Card, Upload } 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 { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { qrcodeUpload } from '/@/api/oem/index';
  import type { FileItem } from '/@/components/Upload/src/typing';
  import type { CityItem, Code } from '../types';
  import { Authority } from '/@/components/Authority';

  export default defineComponent({
    components: {
      Card,
      BasicForm,
      Loading,
      Upload,
      PlusOutlined,
      Authority,
      LoadingOutlined,
    },
    setup() {
      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 customUploadqrcodePic = async ({ file }) => {
        clearValidate('qrcode');
        if (beforeUploadqrcodePic(file)) {
          qrcodePic.value = '';
          loading.value = true;
          const formData = new FormData();
          formData.append('file', file);
          const response = await qrcodeUpload(formData);
          if (response.fileStaticUri) {
            qrcodePic.value = response.fileStaticUri;
            loading.value = false;
          }
        }
      };
      const beforeUploadqrcodePic = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          createMessage.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 / 1024 < 5;
        if (!isLt2M) {
          createMessage.error('图片大小不能超过5MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      // 更新
      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;

          console.log(newFieldValue.qrCode);
          console.log(newFieldValue.codeTown);
          // 表单校验
          let validateArray = [
            'name',
            'abbreviation',
            'officialWebsite',
            'email',
            'synopsis',
            'nameCountry',
            'address',
            'contacts',
            'tel',
            'id',
          ];
          if (newFieldValue.qrCode == undefined) {
            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,
        customUploadqrcodePic,
        beforeUploadqrcodePic,
        registerCustomForm,
        loading,
      };
    },
  });
</script>
