<template>
  <van-nav-bar title="线上报修" safe-area-inset-top>
    <template #left>
      <van-icon
        :name="require('@/assets/arrow-left.svg')"
        size="24"
        @click="backPath"
      />
    </template>
  </van-nav-bar>
  <div class="page_info">
    <van-form
      input-align="right"
      error-message-align="right"
      @submit="onSubmit"
    >
      <van-cell-group :border="false">
        <van-field
          v-model="dataForm.repairPositionName"
          label="报修位置"
          required
          is-link
          placeholder="请选择报修位置"
          clearable
          :rules="[{ required: true, message: '请选择报修位置' }]"
          @click="showRepairPositionPicker = true"
        />
        <van-popup
          v-model:show="showRepairPositionPicker"
          round
          position="bottom"
        >
          <van-cascader
            v-model="dataForm.repairPosition"
            title="请选择报修位置"
            active-color="#2e69eb"
            :options="positionList"
            :field-names="fieldNames"
            @close="showRepairPositionPicker = false"
            @finish="onFinish"
          />
        </van-popup>
        <van-field
          v-model="dataForm.repairRegionName"
          label="报修区域"
          required
          is-link
          placeholder="请选择报修区域"
          clearable
          :rules="[{ required: true, message: '请选择报修区域' }]"
          @click="showRepairRegionPicker = true"
        />
        <van-popup
          v-model:show="showRepairRegionPicker"
          round
          position="bottom"
        >
          <van-picker
            :columns="repairRegionList"
            :columns-field-names="columnsFieldNames"
            @cancel="showRepairRegionPicker = false"
            @confirm="
              (value) => {
                dataForm.repairRegion = value.dictValue;
                dataForm.repairRegionName = value.dictLabel;
                showRepairRegionPicker = false;
              }
            "
          />
        </van-popup>
        <van-field
          v-model="dataForm.repairTypeName"
          label="报修类型"
          required
          is-link
          placeholder="请选择报修类型"
          clearable
          :rules="[{ required: true, message: '请选择报修类型' }]"
          @click="showRepairTypePicker = true"
        />
        <van-popup v-model:show="showRepairTypePicker" round position="bottom">
          <van-picker
            :columns="repairTypeList"
            :columns-field-names="columnsFieldNames"
            @cancel="showRepairTypePicker = false"
            @confirm="
              (value) => {
                dataForm.repairType = value.dictValue;
                dataForm.repairTypeName = value.dictLabel;
                showRepairTypePicker = false;
              }
            "
          />
        </van-popup>
        <van-field
          v-model="dataForm.contactPerson"
          label="联系人"
          required
          placeholder="请输入联系人"
          clearable
          :rules="[{ required: true, message: '请输入联系人' }]"
        />
        <van-field
          v-model="dataForm.contactPhone"
          label="联系电话"
          required
          maxlength="11"
          placeholder="请输入联系电话"
          clearable
          :rules="[{ required: true, message: '请输入联系电话' }]"
        />
        <van-field
          v-model="dataForm.faultDes"
          type="textarea"
          label="故障描述"
          required
          rows="4"
          autosize
          maxlength="1000"
          show-word-limit
          placeholder="请输入故障描述"
          clearable
          :rules="[{ required: true, message: '请输入故障描述' }]"
        />
        <van-cell title="上传照片" :border="false" class="upload_cell">
          <template #value>
            <van-uploader
              v-model="fileList"
              multiple
              :upload-icon="require('@/assets/camera.svg')"
              :max-size="500 * 1024"
              :max-count="10"
              accept="image/jpeg,image/jpg,image/png"
              :before-read="beforeRead"
              :before-delete="beforeDelete"
              :after-read="afterRead"
              @oversize="onOversize"
            />
          </template>
        </van-cell>
      </van-cell-group>
      <van-submit-bar class="save_btn">
        <template #button>
          <van-button block type="primary" native-type="submit">
            提交
          </van-button>
        </template>
      </van-submit-bar>
    </van-form>
  </div>
</template>
<script>
import Api from "@/utils/api";
import { getDictDataList } from "@/utils/index";
export default {
  data() {
    return {
      loading: false,
      fileList: [],
      tempFileList: [],
      positionList: [],
      columnsFieldNames: {
        text: "dictLabel",
        value: "dictValue",
      },
      fieldNames: {
        text: "orgName",
        value: "orgId",
        children: "childrenList",
      },
      showRepairPositionPicker: false,
      showRepairRegionPicker: false,
      showRepairTypePicker: false,
      repairRegionList: [],
      repairTypeList: [],
      dataForm: {
        id: "",
        buildingId: "",
        storeyId: "",
        houseId: "",
        repairPosition: "",
        repairPositionName: "",
        repairRegion: 1,
        repairRegionName: "",
        repairType: 1,
        repairTypeName: "",
        contactPerson: "",
        contactPhone: "",
        faultDes: "",
        faultPics: "",
      },
    };
  },

  created() {
    this.getBuildList();
    this.getRepairTypeList();
    this.getRepairRegionList();
  },

  methods: {
    getRepairTypeList() {
      this.repairTypeList = getDictDataList("RepairType");
    },

    getRepairRegionList() {
      this.repairRegionList = getDictDataList("RepairRegion");
    },

    //获取楼栋
    getBuildList() {
      Api.getBuildInfo().then((res) => {
        if (res.code == 0) {
          this.positionList = res.data[0].childrenList;
        }
      });
    },

    onFinish(val) {
      this.dataForm.buildingId = val.selectedOptions[0].orgId;
      this.dataForm.storeyId = val.selectedOptions[1].orgId;
      this.dataForm.houseId = val.selectedOptions[2].orgId;
      this.dataForm.repairPositionName =
        val.selectedOptions[0].orgName +
        "/" +
        val.selectedOptions[1].orgName +
        "/" +
        val.selectedOptions[2].orgName;
      this.showRepairPositionPicker = false;
    },

    onOversize() {
      this.$toast("单个文件大小不能超过 500kb");
    },

    beforeRead(file) {
      if (file instanceof Array) {
        const obj = file.find(
          (item) =>
            !(
              item.type == "image/jpg" ||
              item.type == "image/jpeg" ||
              item.type == "image/png"
            )
        );
        if (obj) {
          this.$toast("请上传 jpeg、jpg或png 格式图片");
          return false;
        }
      } else {
        const isJPG = file.type == "image/jpg";
        const isJPEG = file.type == "image/jpeg";
        const isPNG = file.type == "image/png";
        if (!(isJPG || isJPEG || isPNG)) {
          this.$toast("请上传 jpeg、jpg或png 格式图片");
          return false;
        }
      }
      return true;
    },

    beforeDelete(file) {
      this.tempFileList = this.tempFileList.filter(
        (item) => item.name != file.file.name
      );
      this.fileList = this.fileList.filter(
        (item) => item.file.name != file.file.name
      );
    },

    afterRead(file) {
      if (file instanceof Array) {
        file.forEach((file) => {
          file.status = "uploading";
          file.message = "上传中...";
          setTimeout(async () => {
            await this.uploadFile(file);
          }, 1000);
        });
      } else {
        file.status = "uploading";
        file.message = "上传中...";
        setTimeout(() => {
          this.uploadFile(file);
        }, 1000);
      }
    },

    uploadFile(file) {
      //  这时候我们创建一个formData对象实例
      const formData = new FormData();
      // 通过append方法添加需要的file
      // 这里需要注意 append(key, value)来添加数据，如果指定的key不存在则会新增一条数据，如果key存在，则添加到数据的末尾
      formData.append("file", file.file);

      // 上传文件、成功后， 把Url 赋值给 field
      Api.uploadFile(formData).then((res) => {
        if (res.code == 0) {
          file.status = "done";
          file.message = "上传成功";
          this.tempFileList.push({ name: file.file.name, url: res.data });
        } else {
          file.status = "failed";
          file.message = "上传失败";
        }
      });
    },

    onSubmit() {
      let tempArr = [];
      this.tempFileList.forEach((item) => {
        tempArr.push(item.url);
      });
      this.dataForm.faultPics = tempArr.join(",");
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
      });
      Api.repairSave(this.dataForm).then((res) => {
        this.$toast.clear();
        if (res.code == 0) {
          this.$toast.success("保存成功");
        } else {
          this.$toast.fail("保存失败");
        }
      });
    },

    backPath() {
      this.$router.back();
    },
  },
};
</script>
<style lang="scss" scoped>
.page_info {
  margin-top: 12px;
  /deep/ {
    .upload_cell {
      .van-cell__title {
        flex: unset;
      }
      .van-cell__value {
        margin-left: 8px;
        text-align: center;
      }
    }
  }
}
</style>