<!-- 应急物资分类表 -->
<template>
  <basic-container>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库全称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库简称" prop="abbreviationName">
            <el-input v-model="ruleForm.abbreviationName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库类型" prop="warehouseType">
            <el-select v-model="ruleForm.warehouseType" multiple clearable>
              <el-option v-for="item in warehouse_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理机构" prop="gljg">
            <el-input v-model="gljg" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址" prop="deptMergeAddress">
            <el-cascader
              clearable
              v-model="ruleForm.deptMergeAddress"
              placeholder="请选择"
              :options="addressOption"
              :props="{ value: 'code', label: 'name' }"
              style="width: 100%"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label=" " prop="deptAddress" label-width="1">
            <el-input v-model="ruleForm.deptAddress" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人信息" prop="legalPerson">
            <el-input v-model="ruleForm.legalPerson" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="deptPhone">
            <el-input v-model="ruleForm.deptPhone" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="库区图" prop="reservoirImg">
            <el-upload
              class="avatar-uploader"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.reservoirImg" :src="ruleForm.reservoirImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="operationbox">
        <el-button type="success" @click="submitForm(ruleFormRef)">保存</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </div>
    </el-form>
  </basic-container>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getAddress, deptDetail, updateDept } from "@/api/basicInfo/index";
import type { UploadProps } from "element-plus";
import { useDict } from "@/hooks/dict";
const { warehouse_type } = useDict("warehouse_type");
import { ElMessage } from "element-plus";
import { sysFile } from "@/api/inAndOut/formationFilling/in";

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  name: "",
  abbreviationName: "",
  warehouseType: "",
  deptMergeAddress: [],
  deptAddress: "",
  legalPerson: "",
  deptPhone: "",
  reservoirImg: ""
});
const fileName = ref("");
const gljg = ref("");
const rules = reactive({
  name: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  warehouseType: [
    {
      required: true,
      message: "请选择，不能为空",
      trigger: "change"
    }
  ],
  deptMergeAddress: [
    {
      required: true,
      message: "请选择，不能为空",
      trigger: "change"
    }
  ],
  legalPerson: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  deptPhone: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  reservoirImg: [{ required: true, message: "请填写，不能为空", trigger: "blur" }]
});
//提交方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let postData = {
        ...ruleForm.value,
        deptProvince: ruleForm.value.deptMergeAddress[0],
        deptCity: ruleForm.value.deptMergeAddress[1],
        deptArea: ruleForm.value.deptMergeAddress[2],
        deptMergeAddress: JSON.stringify(ruleForm.value.deptMergeAddress),
        warehouseType: JSON.stringify(ruleForm.value.warehouseType),
        reservoirImg: fileName.value
      };
      console.log(postData);
      updateDept(postData).then((res: any) => {
        if (res.code === 0) {
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
const addressOption = ref([]);
const getOption = () => {
  getAddress().then((res: any) => {
    if (res.code === 0) {
      addressOption.value = res.data;
    }
  });
};
const createdMth = async () => {
  const deptId = JSON.parse(sessionStorage.getItem("userInfo")).deptId;
  let deptData = await deptDetail(deptId);
  ruleForm.value = deptData.data;
  handlePreview(ruleForm.value.reservoirImg);
  if (deptData.data.parentId != "0") {
    let parentDept = await deptDetail(deptData.data.parentId);
    ruleForm.value.warehouseType = JSON.parse(deptData.data.warehouseType);
    ruleForm.value.deptMergeAddress = JSON.parse(deptData.data.deptMergeAddress);
    gljg.value = parentDept.data.abbreviationName;
  }
};
getOption();
createdMth();
const handlePreview = (filePart) => {
  sysFile(filePart).then((res: any) => {
    const blob = new Blob([res], { type: "image/png" });
    const bFile = URL.createObjectURL(blob);
    fileName.value = filePart;
    ruleForm.value.reservoirImg = bFile;
  });
};
const handleChange = (value) => {
  console.log(JSON.stringify(value));
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  createdMth();
};

/*----------------------库区图-----------------*/
//附件部分
const myHeader = { Authorization: "Bearer " + sessionStorage.getItem("access_token") };
const fileUrl = "/admin/sysFile/uploadVoucher";
let paramsData = reactive({
  bucket: "bound"
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  handlePreview(response.data.fileName);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // if (rawFile.type !== "image/jpeg") {
  //   ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error("Avatar picture size can not exceed 2MB!");
  //   return false;
  // }
  return true;
};
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
