<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改应急管理' : '新建应急管理'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 6, sm: 6, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 22, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="项目名称" name="projectName">
            <ProjectSelectModel
              :placeholder="`请选择项目`"
              v-model:value="form.projectName"
              @done="chooseProject"
            />
          </a-form-item>
          <a-form-item label="问题描述">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入问题描述"
              v-model:value="form.problem"
            />
          </a-form-item>
          <a-form-item label="处理方法">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入问题描述"
              v-model:value="form.processingMethod"
            />
          </a-form-item>
          <a-form-item label="上传图片" name="files">
            <ele-image-upload
              v-model:value="files"
              :item-style="{ width: '90px', height: '90px' }"
              :limit="20"
              @upload="onUpload"
            />
          </a-form-item>
          <a-form-item label="是否更换配件" name="menuType">
            <a-radio-group
              v-model:value="form.replaceAccessories"
              @change="onReplaceAccessories"
            >
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="所在地" name="address">
            <a-input
              allow-clear
              placeholder="请输入项目地址"
              v-model:value="form.address"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import { FormInstance, Rule, RuleObject } from "ant-design-vue/es/form";
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import type { Security } from '@/api/tower/security/model';
  import { addSecurity, updateSecurity } from '@/api/tower/security';
  import { Project } from '@/api/tower/project/model';
  import type { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
  import { uploadFile } from "@/api/system/file";
  import { pop } from "echarts/types/src/component/dataZoom/history";

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

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

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

  const formRef = ref<FormInstance | null>(null);
  // 是否是修改
  const isUpdate = ref(false);
  // 提交状态
  const loading = ref(false);
  // 已上传数据, 可赋初始值用于回显
  const files = ref<ItemType[]>([]);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Security>({
    securityId: undefined,
    type: 2,
    problem: '',
    processingMethod: '',
    files: '',
    replaceAccessories: 0,
    projectId: undefined,
    projectName: undefined,
    securityCode: undefined,
    address: '',
    status: 0,
    comments: '',
    sortNumber: 100
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
      projectName: [
      {
        required: true,
        message: '请选项项目',
        type: 'string',
        trigger: 'blur',
          validator: async (_rule: RuleObject, value: string) => {
              if (value == "") {
                  return Promise.reject("请输入项目名称");
              }
              return Promise.resolve();
          }
      }
    ],
    model: [
      {
        required: true,
        message: '请输入设备型号',
        type: 'string',
        trigger: 'blur'
      }
    ],
    yearLife: [
      {
        required: true,
        message: '请输入设备使用年限',
        type: 'number',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });

  const onReplaceAccessories = (e) => {
      form.replaceAccessories = e.target.value;
  }

  // 上传文件
  const onUpload = (d: ItemType) => {
      uploadFile(<File>d.file)
          .then((result) => {
              // form.files = result.thumbnail;
              files.value.push({
                  uid: result.id,
                  url: result.url,
                  status: "done"
              })
              message.success('上传成功');
          })
          .catch((e) => {
              message.error(e.message);
          });
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const categoryForm = {
          ...form,
            files: JSON.stringify(files.value)
        };
        const saveOrUpdate = isUpdate.value ? updateSecurity : addSecurity;
        saveOrUpdate(categoryForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

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

  const chooseProject = (row: Project) => {
    form.projectId = row.projectId;
    form.projectName = row.projectName;
    form.address = row.projectAddress;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
          files.value = [];
        if (props.data) {
          assignFields({
            ...props.data
          });
            if(props.data.replaceAccessories == 1){
                form.replaceAccessories = 1
            }else {
                form.replaceAccessories = 0
            }
            if (props.data.files) {
                const arr = JSON.parse(props.data.files);
                arr.map((d, i) => {
                    files.value.push({
                        uid: d.uid,
                        url: d.url,
                        status: 'done'
                    });
                });
            }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>

<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
