<template>
  <BasicModal
    :maskClosable="false"
    :width="800"
    @register="registerModal"
    v-bind="$attrs"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm class="station-info" @register="registerForm">
      <template #Upload="{ model, field }">
        <div class="clearfix">
          <a-upload
            v-show="uploadType == 0"
            :before-upload="beforeUpload"
            name="file"
            list-type="picture-card"
            v-model:file-list="fileList"
            @preview="handlePreview"
            @change="onChangeImg"
            :customRequest="selfUpload"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-upload
            v-show="uploadType == 1"
            :before-upload="beforeUpload"
            name="file"
            list-type="picture-card"
            v-model:file-list="fileList2"
            @preview="handlePreview"
            @change="onChangeImg"
            :customRequest="selfUpload2"
          >
            <div v-if="fileList2.length < 8">
              <plus-outlined />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getNewStation, getUpdateTree, UploadImg } from '/@/api/swHome/index';
  import { findDictItemByCode } from '/@/api/system/dict';
  import { useUserStore } from '/@/store/modules/user';
  import { getAppEnvConfig } from '/@/utils/env';
  const { VITE_GLOB_BASE_IMG } = getAppEnvConfig();
  const userStore = useUserStore();
  const { createMessage } = useMessage();
  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    setup(_, { emit }) {
      const previewVisible = ref<boolean>(false);
      const previewImage = ref<string | undefined>(
        'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
      );
      const fileList = ref([
        // {
        //   status: 'done',
        //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        // },
      ]);
      const fileList2 = ref([
        // {
        //   status: 'done',
        //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        // },
      ]);
      let accountFormSchema = ref([
        {
          field: 'stcd',
          label: '测站代码',
          component: 'Input',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'name',
          label: '测站名称',
          component: 'Input',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'st_type',
          label: '测站类型',
          component: 'ApiSelect',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            placeholder: '请选择测站类型',
            api: findDictItemByCode,
            params: {
              dictCode: 'station_type',
            },
            labelField: 'itemText',
            valueField: 'itemValue',
          },
        },
        {
          field: 'catchment_area',
          label: '集水面积(k㎡)',
          component: 'Input',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'lng',
          label: '经纬度',
          component: 'Input',
          colProps: { span: 7 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'lat',
          label: ',',
          component: 'Input',
          colProps: { span: 5 },
          // required: true,
          componentProps: {
            maxLength: 30,
          },
        },

        {
          field: 'elevation',
          label: '海拔(m)',
          component: 'Input',
          colProps: { span: 12 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'basin',
          label: '所属流域',
          component: 'Input',
          colProps: { span: 24 },
          required: true,
          defaultValue: '906',
          componentProps: {
            maxLength: 30,
            disabled: true,
          },
        },
        {
          field: 'position',
          label: '测站地址',
          component: 'Input',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            maxLength: 30,
            // disabled: true,
          },
        },
        {
          field: 'img_type',
          label: '图片',
          component: 'ApiSelect',
          colProps: { span: 10 },
          required: true,
          componentProps: {
            placeholder: '请选择测站类型',
            api: findDictItemByCode,
            params: {
              dictCode: 'station_img_type',
            },
            labelField: 'itemText',
            valueField: 'itemValue',
            onChange:(value) => {
              uploadType.value = value
            }
          },
        },
        {
          field: 'img',
          // label: '图片',
          component: 'Upload',
          colProps: { span: 14 },
          slot: 'Upload',
        },
        {
          field: 'note',
          label: '备注',
          component: 'InputTextArea',
          colProps: { span: 24 },
          componentProps: {
            maxLength: 255,
            placeholder: '请输入备注',
          },
        },
      ]);
      const uploadType = ref('0') // 0 是现场图片，1是监测布置图片
      const isUpdate = ref(true);
      const isDetails = ref(false);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        fileList.value = []
        fileList2.value = []
        isDetails.value = !!data?.details;
        isUpdate.value = !!data?.isUpdate;
        if (data?.details) {
          let img_type = ''
          if(data.formData.attr.img_url.length>0){
            img_type = data.formData.attr.img_url[0].img_type
            uploadType.value = data.formData.attr.img_url[0].img_type
            // 图片回显
            data.formData.attr.img_url.forEach((element,index) => {
              if(element.img_type == 0){
                fileList.value.push({
                  uid:index,
                  status: 'done',
                  url:VITE_GLOB_BASE_IMG+element.url,
                  img_type:element.img_type,
                })
              }else{
                fileList2.value.push({
                  uid:index,
                  status: 'done',
                  url:VITE_GLOB_BASE_IMG+element.url,
                  img_type:element.img_type,
                })
              }
            });
          }
          setFieldsValue({
            stcd: data?.formData.attr.stcd,
            name: data?.formData.name,
            st_type: data?.formData.attr.station_type+"",
            catchment_area: data?.formData.attr.catchment,
            lat: data?.formData.attr.lat,
            lng: data?.formData.attr.lng,
            elevation: data?.formData.attr.elevation,
            basin: data?.formData.attr.basin,
            position: data?.formData.attr.position,
            note: data?.formData.attr.note,
            img_type: img_type,
          });
          accountFormSchema.value.forEach((element) => {
            element.componentProps['disabled'] = true;
          });
          updateSchema(accountFormSchema.value);
          return;
        }

        // 编辑
        if (unref(isUpdate)) {
          // 处理图片
          let img_type = ''
          if(data.formData.attr.img_url.length>0){
            img_type = data.formData.attr.img_url[0].img_type
            uploadType.value = data.formData.attr.img_url[0].img_type
            // 图片回显
            data.formData.attr.img_url.forEach((element,index) => {
              if(element.img_type == 0){
                fileList.value.push({
                  uid:index,
                  status: 'done',
                  url:VITE_GLOB_BASE_IMG+element.url,
                  img_type:element.img_type,
                })
              }else{
                fileList2.value.push({
                  uid:index,
                  status: 'done',
                  url:VITE_GLOB_BASE_IMG+element.url,
                  img_type:element.img_type,
                })
              }
            });
          }
          setFieldsValue({
            stcd: data?.formData.attr.stcd,
            name: data?.formData.name,
            st_type: data?.formData.attr.station_type+"",
            catchment_area: data?.formData.attr.catchment,
            lat: data?.formData.attr.lat,
            lng: data?.formData.attr.lng,
            elevation: data?.formData.attr.elevation,
            basin: data?.formData.attr.basin,
            position: data?.formData.attr.position,
            note: data?.formData.attr.note,
            img_type: img_type,
          });
        } else {
          await resetFields();
          setFieldsValue({
            img_type:'0'
          })
          uploadType.value = '0'
        }
        accountFormSchema.value.forEach((element) => {
          element.componentProps['disabled'] = false;
        });
        updateSchema(accountFormSchema.value);
      });
      const [
        registerForm,
        { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue },
      ] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });
      const getTitle = computed(() => {
        if(unref(isDetails)){
          return '详情'
        }
        if(!unref(isUpdate)){
          return '新增'
        }else{
          return '编辑'
        }
      });
      async function handleSubmit() {
        setModalProps({ confirmLoading: true });
        if(unref(isDetails)){
          setModalProps({ confirmLoading: false });
          closeModal();
          return
        };
        try {
          const values = await validate([
            'stcd',
            'name',
            'st_type',
            'catchment_area',
            'lat',
            'lng',
            'elevation',
            'basin',
            'position',
            'img_type',
          ]);

          let formData = getFieldsValue();
          formData.type = 'station';
          formData.attr = {
            stcd: formData.stcd,
            station_type: formData.st_type,
            catchment: formData.catchment_area,
            lat: formData.lat,
            lng: formData.lng,
            elevation: formData.elevation,
            basin: formData.basin,
            position: formData.position,
            note: formData.note || '',
            img_type: formData.img_type,
            img_url: [],
          };
          delete formData.stcd;
          delete formData.st_type;
          delete formData.catchment_area;
          delete formData.lat;
          delete formData.lng;
          delete formData.elevation;
          delete formData.basin;
          delete formData.position;
          delete formData.note;
          delete formData.img_type;
          console.log(formData);
          // 处理图片
          console.log(fileList.value);
          fileList.value.forEach((element) => {
            if (element.status === 'done') {
              if(element.response){
                formData.attr.img_url.push({
                  img_type: element.response.img_type,
                  url: element.response.data[0],
                });
              }else{
                formData.attr.img_url.push({
                  img_type: element.img_type,
                  url: element.url.split(VITE_GLOB_BASE_IMG).join("")
                });
              }
              
            }
          });
          fileList2.value.forEach((element) => {
            if (element.status === 'done') {
              if(element.response){
                formData.attr.img_url.push({
                  img_type: element.response.img_type,
                  url: element.response.data[0],
                });
              }else{
                formData.attr.img_url.push({
                  img_type: element.img_type,
                  url: element.url.split(VITE_GLOB_BASE_IMG).join("")
                });
              }
            }
          });
          // 新增
          if (!unref(isUpdate)) {
            let resData = await getNewStation(formData);
            if (resData.code != 200) {
              createMessage.warning(resData.msg);
              return false;
            }
            console.log(resData);
          } else {
            const userInfo = await userStore;
            formData.attr.user = userInfo.userInfo.username;
            //编辑
            let resData = await getUpdateTree(formData);
            if (resData.code != 200) {
              createMessage.warning(resData.msg);
              return false;
            }
          }
          closeModal();
          emit('success');
          createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
        } finally {
          setTimeout(() => {
            setModalProps({ confirmLoading: false });
          }, 300);
        }
      }
      const handleCancel = () => {
        previewVisible.value = false;
      };
      const beforeUpload = async (file): Promise<boolean> => {
        // 坑：必须要返回一个 Promise，promise 中 必须返回false 才能阻止上传，通过校验必须返回true和 resolve 否则会阻止上传
        return new Promise((resolve) => {
          let fieldsValue = getFieldsValue();
          const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
          if (!isJpgOrPng) {
            createMessage.error('只能上传JPG/PNG格式文件!');
            return false;
          }
          const isLt10M = file.size / 1024 / 1024 < 10;
          if (!isLt10M) {
            createMessage.error('图片大小不能超过10MB!');
            return false;
          }
          if (!fieldsValue.stcd) {
            createMessage.error('请先输入测站代码!');
            return false;
          }
          if (!fieldsValue.name) {
            createMessage.error('请先输入测站名称!');
            return false;
          }
          if (fieldsValue.img_type != 0 && fieldsValue.img_type != 1) {
            createMessage.error('请先选择图片类型!');
            return false;
          }
          resolve(true);
          return true;
        });
      };
      const onChangeImg = async (info) => {
        let fileListArr = [];
        // info.fileList.forEach((element) => {
        //   if (element.status === 'done') {
        //     fileList.value.push({
        //       status: 'done',
        //       url: element.url ? element.url : element.response.data[0],
        //     });
        //   }
        // });
        // fileList.value = fileListArr;
      };
      const handlePreview = () => {
        console.log(1);
      };
      const selfUpload = async (data) => {
        let fieldsValue = getFieldsValue();
        let files = new FormData();
        files.append('file', data.file);
        files.append('type', fieldsValue.img_type);
        files.append(
          'name',
          `${fieldsValue.stcd}-${fieldsValue.img_type == 0 ? '现场图片' : '监测布置图片'}-${
            fieldsValue.name
          }.png`
        );
        let img = await UploadImg(files).then((res) => {
          return res;
        });
        if (img.code == 200) {
          img.img_type = fieldsValue.img_type;
          data.onSuccess(img, data.file);
        } else {
          data.onError(img, data.file);
        }
      };
      const selfUpload2 = async (data) => {
        let fieldsValue = getFieldsValue();
        let files = new FormData();
        files.append('file', data.file);
        files.append('type', fieldsValue.img_type);
        files.append(
          'name',
          `${fieldsValue.stcd}-${fieldsValue.img_type == 0 ? '现场图片' : '监测布置图片'}-${
            fieldsValue.name
          }.png`
        );
        let img = await UploadImg(files).then((res) => {
          return res;
        });
        if (img.code == 200) {
          img.img_type = fieldsValue.img_type;
          data.onSuccess(img, data.file);
        } else {
          data.onError(img, data.file);
        }
      };

      return {
        registerModal,
        getTitle,
        handleSubmit,
        registerForm,
        fileList,
        fileList2,
        previewVisible,
        handleCancel,
        previewImage,
        handlePreview,
        onChangeImg,
        selfUpload,
        selfUpload2,
        beforeUpload,
        uploadType,
      };
    },
  });
</script>
<style>
  .station-info .ant-col:nth-child(6) .ant-form-item-label {
    width: 20px !important;
  }
</style>
