<template>
  <div class="slider-right">
    <!-- <div class="top-title">{{ $router.currentRoute.meta.title }}</div> -->
    <TopBackTitle></TopBackTitle>
    <div class="table-box">
      <div class="form-row-title">缺陷信息</div>
      <div class="defectInformation">
        <el-row>
          <el-col :span="8">
            <div class="tc-text2">堤防名称：</div>
            <div class="tc-text1">{{ form.dikeName }}</div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">堤防巡查责任人：</div>
            <div class="tc-text1">{{ form.createName }}</div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">防治类别：</div>
            <div class="tc-text1">
              {{getDictLabelName(form.category, "maintenanceCategory") }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">堤防巡查开始/结束时间：</div>
            <div class="tc-text1">{{ form.startDate }}/{{ form.endDate }}</div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">检查区域：</div>
            <div class="tc-text1">{{ form.partsName }}</div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">问题位置：</div>
            <div class="tc-text1">{{ form.position }}</div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">问题等级：</div>
            <div class="tc-text1">
              {{getDictLabelName(form.problemLevel, "maintenanceLevel") }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="tc-text2">具体描述：</div>
            <div class="tc-text1">{{ form.content }}</div>
          </el-col>
          <el-col :span="24">
            <div class="tc-text2">缺陷图片：</div>
            <div class="tc-text1">
              <el-image
                v-for="item in form.problemImages"
                style="width: 240px; height: 135px;margin-right: 16px;"
                :src="item"
                :preview-src-list="form.problemImages">
              </el-image>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="form-row-title">处置记录</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="top">
        <el-row :gutter="48">
          <el-col :span="8">
            <el-form-item label="处置责任人:" prop="userName">
              <el-input
                disabled
                placeholder="请输入内容"
                v-model="form.userName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处置时间：" prop="time">
              <el-date-picker
                size="small"
                class="ml-10"
                style="width: 100%;"
                v-model="form.time"
                type="daterange"
                :disabled="$route.query.mode === 'check'"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="处置详情：" prop="describe">
              <el-input
                type="textarea"
                :rows="4"
                :disabled="$route.query.mode === 'check'"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
                v-model="form.describe">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件：" prop="images">
          <el-upload
            class=""
            action="#"
            style="margin-bottom: 16px;"
            :http-request="handleUploadProject1"
            :before-upload="beforeUploadProject1"
            :show-file-list="false"
            accept=".png,.jpg,.tif,.gif"
          >
            <div style="display:flex;">
              <el-button
                :disabled="$route.query.mode === 'check'"
                style="margin-right: 16px;"
                size="small"
                type="primary"
                v-hasPermi="['df:run:pestanimal2:maintenance:detail:attachment']"
              >上传</el-button>
              <div slot="tip" style="margin-top: 0" class="el-upload__tip">文件上传支持.jpg.png.tif.gif 单张图片5M以内，最多上传3张</div>
            </div>
          </el-upload>
          <el-image
            v-for="item in form.images"
            style="width: 240px; height: 135px;margin-right: 16px;"
            :src="item.url"
            :preview-src-list="form.images">
          </el-image>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom-btns" v-if="$route.query.mode !== 'check'">
      <el-button
        type="primary"
        @click="handleSave(true)"
        v-hasPermi="['df:run:pestanimal2:maintenance:detail:submit']"
      >保存并提交</el-button
      >
      <el-button
        type="primary"
        @click="handleSave(false)"
        v-hasPermi="['df:run:pestanimal2:maintenance:detail:save']"
      >保存</el-button
      >
      <el-button @click="$router.go(-1)">返回</el-button>
    </div>
  </div>
</template>
<script>
import TopBackTitle from "@/components/TopBackTitle/index.vue";
import { calcTableHeight } from "@/mixins/calcTableHeight";
import SyMixMap from "@/views/components/SyMixMap.vue";
import { uploadFileData } from "@/api/system/upload";
import { getV2Yh, postV2Yh, gettV2Record } from "@/api/dike/pestAnimalControl2";
import { getDictMapData } from "@/api/system/dict/data";
import { mapGetters } from "vuex";

export default {
  components: {
    SyMixMap,
    TopBackTitle,
  },
  mixins: [calcTableHeight],
  data() {
    return {
      entries: {},
      traceList: [],
      maintenanceCategory: [],
      maintenanceLevel: [],
      tableData: [{
        nspectionLocation: '堤坡与戗台',
        inspectionContent: '是否坚实平整',
      }],
      form: {
        images: [],
        createName: '',
        userName: '',
        dikeName: '',
        category: '',
        parts: '',
        partsName: '',
        content: '',
        describe: '',
        position: '',
        problemImages: '',
        problemLevel: '',
        createUid: '',
        dikeCode: '',
        projectType: '',
        type: '',
        time: [],
        scope: '',
      },
      rules: {
        userName: [{required: true}],
        dikeName: [{required: true}],
        inspectionCategory: [{required: true}],
        time: [{required: true, message: "请选择巡查时间", trigger: "change"}],
        describe: [{required: true, message: "输入巡查详情", trigger: "change"}],
      }
    };
  },
  created() {
    this.getDicts("patrol_maintenance_category").then((response) => {
      this.maintenanceCategory = response.data;
    });
    this.getDicts("patrol_maintenance_level").then((response) => {
      this.maintenanceLevel = response.data;
    });
  },
  mounted() {
    this.initData()
  },
  computed: {
    ...mapGetters({
      userId: "uid",
      userName: "name",
    }),
  },
  methods: {
    async initData() {
      const checking = await gettV2Record(this.$route.query.recordId)
      this.form.createName = checking.data.createName
      this.form.userName = this.userName
      this.form.userId = this.userId
      this.form.dikeName = checking.data.dikeName
      this.form.checkingId = checking.data.checkingId
      this.form.checkingName = checking.data.checkingName
      this.form.status = checking.data.status
      this.form.problems = checking.data.problems
      this.form.category = checking.data.category
      this.form.createUid = checking.data.createUid
      this.form.dikeCode = checking.data.dikeCode
      this.form.projectType = checking.data.projectType
      this.form.type = checking.data.type
      this.form.startDate = checking.data.startDate
      this.form.endDate = checking.data.endDate
      checking.data.problems.forEach(item => {
        if(item.id === this.$route.query.defectId) {
          this.form.content = item.content
          this.form.position = item.position
          this.form.parts = item.parts
          getDictMapData("df_an_c_classfy").then((res) => {
            let parts = ''
            item.parts.forEach((part) => {
              if (parts) {
                parts = parts + ':' + part
              } else {
                parts = part
              }
            })
            this.form.partsName = res.data[parts]
          })
          this.form.problemLevel = item.problemLevel
          this.form.problemImages = item.problemImages
        }
      })
      if (this.$route.query.id) {
        const ApprovalComment = await getV2Yh(this.$route.query.id)
        this.form.time[0] = ApprovalComment.data.startDate
        this.form.time[1] = ApprovalComment.data.endDate
        this.form.describe = ApprovalComment.data.content
        this.form.time = [...this.form.time]
        this.form.images = ApprovalComment.data.doc.images
      }
    },
    getDictLabelName(type, dictListName) {
      if (!this[dictListName]) return "";
      return (
        this[dictListName].find((item) => item.dictValue === type)?.dictLabel ||
        ""
      );
    },
    // 图片上传后
    handleUploadProject(e, row) {
      const { file } = e;
      let fData = new FormData();
      fData.append("file", file);
      uploadFileData(fData)
        .then((res) => {
          row.url = res.url;
        })
        .catch((err) => {
          console.log("err >>>>>  ", err);
        });
    },
    // 图片上传前
    beforeUploadProject(e, row) {
      const { name, size } = e;
      if (!/\.(jpg|png|jpeg)$/.test(name)) {
        this.$message.warning("文件格式不正确");
        return false;
      }
      if (row.problemImages?.length >= 3) {
        this.$message({
          message: "最多上传3份",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    // 图片上传后
    handleUploadProject1(e, row) {
      const { file } = e;
      let fData = new FormData();
      fData.append("file", file);
      uploadFileData(fData)
        .then((res) => {
          this.form.images.push({
            name: res.name,
            url: res.url
          });
        })
        .catch((err) => {
          console.log("err >>>>>  ", err);
        });
    },
    // 图片上传前
    beforeUploadProject1(e, row) {
      const { name, size } = e;
      if (!/\.(jpg|png|tif|gif)$/.test(name)) {
        this.$message.warning("文件格式不正确");
        return false;
      }
      if (this.form.images?.length >= 3) {
        this.$message({
          message: "最多上传3份",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    deleteTableItem(row) {
      row.url = ''
    },
    handleSave(commit) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            name: this.form.checkingName,
            dikeCode: this.form.dikeCode,
            projectType: this.form.projectType,
            dikeName: this.form.dikeName,
            status: this.form.status,
            type: this.form.type,
            category: this.form.category,
            checkingId: this.form.checkingId,
            content: this.form.describe,
            dutyHolderId: this.form.userId,
            dutyHolderName: this.form.userName,
            problemLevel: this.form.problemLevel,
            problemId: this.$route.query.defectId,
            recordId: this.$route.query.recordId,
            doc: {
              images: this.form.images
            },
            startDate: this.form.time && this.form.time.length > 1 ? this.form.time[0] : '',
            endDate: this.form.time && this.form.time.length > 1 ? this.form.time[1] : '',
          }
          if (this.$route.query.id) {
            data.id = this.$route.query.id
          }
          postV2Yh(data, commit).then(res => {
            this.$message.success('保存成功')
            this.$router.go(-1)
          })
        }
      })

    }
  },
};
</script>
<style lang="scss">
.table-box {
  width: 100%;
  height: calc(100% - 50px - 24px);
  margin-top: 24px;
  padding: 16px;
  padding-bottom: 80px;
  background-color: white;
  overflow: auto;
}
.form-row-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  border-left: 4px solid #36b29e;
  padding-left: 8px;
}
.row-item {
  display: flex;
  font-size: 14px;
  line-height: 22px;
  margin-bottom: 16px;
  & > div {
    width: 50%;
  }
}
.defectInformation {
  .el-row {
    margin-bottom: 16px;
    .el-col {
      margin-bottom: 16px;
    }
  }

}

.tc-text2,.tc-text1 {
  line-height: 22px;
}
</style>
