<!-- 用户编辑弹窗 -->
<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="name">
                <TowerSelectModel
                  :placeholder="`请选择设备名称`"
                  v-model:value="form.name"
                  @done="chooseEquipmentName"
                />
              </a-form-item>
              <a-form-item label="出厂编号" name="factoryNo">
                <a-input
                  allow-clear
                  placeholder="请输入出厂编号(不能重复)"
                  v-model:value="form.factoryNo"
                />
              </a-form-item>
              <a-form-item label="自编号" name="equipmentNo">
                <a-input
                  allow-clear
                  placeholder="请输入设备编号"
                  v-model:value="form.equipmentNo"
                />
              </a-form-item>
              <a-form-item label="剩余使用年限" name="surplusYear">
                <a-input
                  allow-clear
                  placeholder="请输入插件名称"
                  disabled
                  v-model:value="form.surplusYear"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="设备型号" name="model">
                <TowerSelectModel
                  :placeholder="`请选择设备型号`"
                  v-model:value="form.model"
                  @done="chooseEquipmentModel"
                />
              </a-form-item>
              <a-form-item label="出厂日期" name="factoryDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  v-model:value="form.factoryDate"
                />
              </a-form-item>
              <a-form-item label="使用年限" name="lifeYear">
                <a-input
                  allow-clear
                  placeholder="请输入使用年限"
                  v-model:value="form.lifeYear"
                  @change="onLifeYaer"
                />
              </a-form-item>
              <a-form-item label="产权单位" name="company">
                <TowerCompany
                  :placeholder="`请选择租赁单位`"
                  v-model:value="form.company"
                  :customer-type="`产权单位`"
                  @done="chooseCompanyName"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="备案编号" name="filingNo">
                <a-input
                  allow-clear
                  placeholder="请输入备案编号"
                  v-model:value="form.filingNo"
                />
              </a-form-item>
              <a-form-item label="制造厂家" name="manufactor">
                <DictSelect
                  dict-code="Manufacturer"
                  placeholder="请选择制造厂家"
                  v-model:value="form.manufactor"
                />
              </a-form-item>
              <a-form-item label="报废日期" name="scrapDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  v-model:value="form.scrapDate"
                />
              </a-form-item>
              <a-form-item label="备案许可证号" name="licenceNo">
                <a-input
                  allow-clear
                  placeholder="请输入插件名称"
                  v-model:value="form.licenceNo"
                />
              </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="warehouse">
                <SelectWarehouse
                  :placeholder="`请选择仓库`"
                  v-model:value="form.warehouse"
                  @done="chooseWarehouse"
                />
              </a-form-item>
              <a-form-item label="采购日期" name="title">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  v-model:value="form.buyDate"
                />
              </a-form-item>
              <a-form-item label="当前位置" name="currentLocation">
                <a-input
                  allow-clear
                  disabled
                  placeholder="请输入当前位置"
                  v-model:value="form.currentLocation"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="所属人员" name="users">
                <SelectUser
                  :placeholder="`请选择所属人员`"
                  v-model:value="form.users"
                  @done="chooseUsers"
                />
              </a-form-item>
              <a-form-item label="安全管理部门" name="organization">
                <SelectOrganization
                  :placeholder="`请选择所属部门`"
                  v-model:value="form.organization"
                  @done="chooseOrganization"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="设备来源" name="source">
                <a-input
                  allow-clear
                  placeholder="请输入设备来源"
                  v-model:value="form.source"
                />
              </a-form-item>
              <a-form-item label="机号" name="machineNo">
                <a-input
                  allow-clear
                  placeholder="请输入插件名称"
                  v-model:value="form.machineNo"
                />
              </a-form-item>
              <a-form-item label="是否外协标识" name="isOutOrg">
                <a-switch v-model:checked="form.isOutOrg" />
              </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="designHeight">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入设计高度"
                  v-model:value="form.designHeight"
                />
                <span class="ml-10">m</span>
              </a-form-item>
              <a-form-item label="独立高度" name="height">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入独立高度"
                  v-model:value="form.height"
                />
                <span class="ml-10">m</span>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 16 }
              "
            >
              <a-form-item label="额定载重" name="ratedLoad">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入额定载重"
                  v-model:value="form.ratedLoad"
                />
                <span class="ml-10">T</span>
              </a-form-item>
              <a-form-item label="最大幅度处额定载重" name="maxRatedLoad">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入最大幅度处额定载重"
                  v-model:value="form.maxRatedLoad"
                />
                <span class="ml-10">T</span>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="最大起升高度(m)" name="maxLiftingHeight">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入最大起升高度(m)"
                  v-model:value="form.maxLiftingHeight"
                />
                <span class="ml-10">m</span>
              </a-form-item>
              <a-form-item label="臂长" name="armLength">
                <a-input-number
                  allow-clear
                  :min="0"
                  style="width: 200px"
                  placeholder="请输入臂长"
                  v-model:value="form.armLength"
                />
                <span class="ml-10">m</span>
              </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-form-item label="备案证书" name="parentId">
                <a-upload
                  v-model:file-list="file5"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile5"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="整机性能参数表" name="parentId">
                <a-upload
                  v-model:file-list="file6"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile6"
                >
                  <a-button>
                    <upload-outlined />
                    上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="其他" name="parentId">
                <a-upload
                  v-model:file-list="file7"
                  name="file"
                  action="https://file.wsdns.cn/api/file/image"
                  :headers="{ Authorization: token }"
                  @change="onFile7"
                >
                  <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 {
    addTowerEquipment,
    updateTowerEquipment
  } from '@/api/tower/equipment';
  import { TowerEquipment } from '@/api/tower/equipment/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { UploadOutlined } from '@ant-design/icons-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?: TowerEquipment | 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<TowerEquipment>({
    equipmentId: undefined,
    name: undefined,
    model: undefined,
    equipmentNo: '',
    factoryNo: '',
    factoryDate: '',
    manufactor: undefined,
    company: '',
    lifeYear: undefined,
    surplusYear: 3,
    scrapDate: '',
    licenceNo: '',
    organization: undefined,
    warehouse: undefined,
    source: undefined,
    buyDate: '',
    currentLocation: '',
    designHeight: undefined,
    height: undefined,
    ratedLoad: '',
    files: '[]',
    file1: '[]',
    file2: '[]',
    file3: '[]',
    file4: '[]',
    file5: '[]',
    file6: '[]',
    file7: '[]',
    filingNo: '',
    machineNo: '',
    users: '',
    isOutOrg: false,
    status: undefined,
    comments: '',
    userId: undefined,
    deleted: undefined,
    tenantId: undefined,
    createTime: undefined,
    maxRatedLoad: '',
    maxLiftingHeight: '',
    armLength: ''
  });

  /* 更新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 onFile5 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file5.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file5 = JSON.stringify(file5.value);
  };
  const onFile6 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file6.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file6 = JSON.stringify(file6.value);
  };
  const onFile7 = (info: FileInfo) => {
    let resFileList = [...info.fileList];
    file7.value = resFileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
    form.file7 = JSON.stringify(file7.value);
  };

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

  const chooseEquipmentModel = (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
          ? updateTowerEquipment
          : addTowerEquipment;
        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>
