<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑设备' : '添加设备'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-card title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="防坠器编号" name="code">
                <a-input
                  allow-clear
                  placeholder="请输入防坠器编号"
                  v-model:value="form.code"
                />
              </a-form-item>
              <a-form-item label="防坠器型号" name="model">
                <a-input
                  allow-clear
                  placeholder="请输入防坠器型号"
                  v-model:value="form.model"
                />
              </a-form-item>
              <a-form-item label="制造厂家" name="factory">
                <a-input
                  allow-clear
                  placeholder="factory"
                  v-model:value="form.factory"
                />
              </a-form-item>
              <a-form-item label="产权单位" name="company">
                <TowerCompany
                  :placeholder="`请选择产权单位`"
                  v-model:value="form.company"
                  :customer-type="`产权单位`"
                  @done="chooseCompanyName"
                />
              </a-form-item>
              <a-form-item label="出厂日期" name="factoryDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD 00:00:00"
                  placeholder="请选择日期"
                  v-model:value="form.factoryDate"
                />
              </a-form-item>
              <a-form-item label="报废日期" name="discardDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD 00:00:00"
                  placeholder="请选择日期"
                  v-model:value="form.discardDate"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="附件信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="出厂报告" name="parentId">
                <a-upload
                  v-model:file-list="file1"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile1"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="合格证" name="parentId">
                <a-upload
                  v-model:file-list="file2"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile2"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="出厂铭牌" name="parentId">
                <a-upload
                  v-model:file-list="file3"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile3"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="发票" name="parentId">
                <a-upload
                  v-model:file-list="file4"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile4"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addTowerFall, updateTowerFall } from '@/api/tower/fall';
  import { TowerFall } from '@/api/tower/fall/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import DictSelect from '@/views/search/components/dict-select.vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { TOKEN_STORE_NAME } from '@/config/setting';
  import { Warehouse } from '@/api/tower/warehouse/model';
  import { User } from '@/api/user/model';
  import { Organization } from '@/api/system/organization/model';
  import { Customer } from '@/api/oa/customer/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  const formRef = ref<FormInstance | null>(null);

  interface FileItem {
    uid: string;
    name?: string;
    status?: string;
    response?: Response;
    thumbUrl?: string;
    downloadUrl?: string;
    url: string;
  }

  interface FileInfo {
    file: FileItem;
    fileList: FileItem[];
  }

  // 文件上传
  const file1 = ref<FileItem[]>();
  const file2 = ref<FileItem[]>();
  const file3 = ref<FileItem[]>();
  const file4 = ref<FileItem[]>();
  const file5 = ref<FileItem[]>();
  const file6 = ref<FileItem[]>();
  const file7 = ref<FileItem[]>();

  // token
  const token = localStorage.getItem(TOKEN_STORE_NAME);

  // 表单信息
  const form = reactive<TowerFall>({
    id: undefined,
    code: undefined,
    model: undefined,
    factory: '',
    factoryDate: '',
    discardDate: undefined,
    file1: '[]',
    file2: '[]',
    file3: '[]',
    file4: '[]',
    users: '',
    status: undefined,
    comments: '',
    userId: undefined,
    deleted: undefined,
    tenantId: undefined,
    createTime: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请输入设备',
        trigger: 'blur'
      }
    ],
    model: [
      {
        required: true,
        type: 'string',
        message: '请输入设备型号',
        trigger: 'blur'
      }
    ],
    factoryNo: [
      {
        required: true,
        type: 'string',
        message: '请输入出厂编号',
        trigger: 'blur'
      }
    ]
  });

  const { resetFields } = useForm(form, rules);

  const onLifeYaer = () => {
    form.surplusYear = form.lifeYear;
  };
  // const onFactoryDate = () => {
  //   form.scrapDate = form.factoryDate;
  // };

  const onFile1 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file1.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file1 = JSON.stringify(file1.value);
  };
  const onFile2 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file2.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file2 = JSON.stringify(file2.value);
  };
  const onFile3 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file3.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file3 = JSON.stringify(file3.value);
  };
  const onFile4 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file4.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file4 = JSON.stringify(file4.value);
  };

  const chooseFallName = (data) => {
    form.name = data.name;
    form.model = data.model;
  };

  const chooseFallModel = (data) => {
    form.name = data.name;
    form.model = data.model;
  };

  const chooseWarehouse = (data: Warehouse) => {
    console.log(data);
    form.warehouse = data.warehouseName;
    form.currentLocation = data.address;
  };

  const chooseUsers = (data: User) => {
    form.users = data.nickname;
  };

  const chooseOrganization = (data: Organization) => {
    form.organization = data.organizationName;
  };

  const chooseCompanyName = (data: Customer) => {
    form.company = data.customerName;
  };

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

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.file1) {
            file1.value = JSON.parse(props.data.file1);
          }
          if (props.data.file2) {
            file2.value = JSON.parse(props.data.file2);
          }
          if (props.data.file3) {
            file3.value = JSON.parse(props.data.file3);
          }
          if (props.data.file4) {
            file4.value = JSON.parse(props.data.file4);
          }
          if (props.data.file5) {
            file5.value = JSON.parse(props.data.file5);
          }
          if (props.data.file6) {
            file6.value = JSON.parse(props.data.file6);
          }
          if (props.data.file7) {
            file7.value = JSON.parse(props.data.file7);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less"></style>

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