<template>
  <div class="detail-page">
    <el-form
      ref="formRef"
      label-position="top"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <div class="form-row-title">堤防选择</div>
      <div class="flex items-start">
        <el-form-item label="选择堤防" prop="dikeName">
          <el-select
            :disabled="!canEdit"
            class="w-240"
            size="small"
            remote
            filterable
            reserve-keyword
            :maxlength="50"
            :remote-method="handleGetRemoteDikeMethod"
            @focus="handleGetRemoteDikeMethod('')"
            @change="handleChangeDike"
            v-model="formData.dikeName"
            placeholder="请选择堤防"
          >
            <el-option
              v-for="item in dikeList"
              :key="item.id"
              :label="item.dikeName"
              :value="item.dikeName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="堤防类型" prop="dikeType" class="ml-24">
          <el-select
            v-model="formData.dikeType"
            :disabled="true"
            class="w-240"
            size="small"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="堤防巡查责任人" prop="dutyHolder" class="ml-24">
          <el-input
            class="w-240"
            size="small"
            v-model="formData.dutyHolder"
            :disabled="true"
            placeholder=""
          ></el-input>
        </el-form-item>
      </div>
      <div class="form-row-title">巡查计划设置</div>
      <div class="flex items-start">
        <el-form-item label="巡查计划名称" prop="name">
          <el-input
            :disabled="!canEdit"
            class="w-240"
            size="small"
            v-model="formData.name"
            placeholder="请输入名称"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡查计划类型" prop="type" class="ml-24">
          <div class="w-240">
            <el-radio-group :disabled="!canEdit" v-model="formData.type">
              <el-radio label="0">年度计划</el-radio>
              <el-radio label="1">月度计划</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="巡查提醒" prop="cycleType" class="ml-24">
          <el-select
            :disabled="!canEdit"
            size="small custom-select-cycleType"
            class="w-100"
            v-model="formData.cycleType"
            placeholder="请选择"
            @change="handleChangeRemindType"
          >
            <el-option label="每月提醒" value="2"> </el-option>
            <el-option label="每周提醒" value="1"> </el-option>
            <el-option label="每日提醒" value="0"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label=""
          style="padding-top: 46px; width: 202px; flex-shrink: 0"
          prop="otherConfig.reminderDays"
          v-if="formData.cycleType == '0'"
        >
          <el-select
            class="w-full custom-select-date"
            :disabled="!canEdit"
            size="small"
            popper-class="custom-select-date-popper"
            multiple
            v-model="formData.otherConfig.reminderDays"
            placeholder="请选择"
          >
            <el-option
              v-for="item in 31"
              :key="item"
              :label="`${item}日`"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label=""
          style="padding-top: 46px"
          v-else-if="formData.cycleType == '1'"
          prop="otherConfig.reminderWeeks"
        >
          <el-checkbox-group
            :disabled="!canEdit"
            size="small"
            v-model="formData.otherConfig.reminderWeeks"
          >
            <el-checkbox-button :label="1">周一</el-checkbox-button>
            <el-checkbox-button :label="2">周二</el-checkbox-button>
            <el-checkbox-button :label="3">周三</el-checkbox-button>
            <el-checkbox-button :label="4">周四</el-checkbox-button>
            <el-checkbox-button :label="5">周五</el-checkbox-button>
            <el-checkbox-button :label="6">周六</el-checkbox-button>
            <el-checkbox-button :label="7">周日</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="" style="padding-top: 46px" prop="reminderTime">
          <el-time-picker
            class="custom-time-piker"
            :disabled="!canEdit"
            size="small"
            v-model="formData.reminderTime"
            value-format="2024-06-05 HH:mm:ss"
            placeholder="选择时间"
          >
          </el-time-picker>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="巡查频率" prop="frequency">
          <el-input
            :disabled="!canEdit"
            class="w-240"
            type="number"
            size="small"
            v-model="formData.frequency"
            placeholder="请输入"
            :max="999"
            :min="0"
          ></el-input>
          <span class="ml-4">次/月</span>
        </el-form-item>
      </div>
      <div class="flex items-start">
        <el-form-item label="附件上传" prop="files">
          <el-upload
            :disabled="!canEdit"
            class=""
            action="#"
            :http-request="handleUpload"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            accept=".docx,.doc,.pdf"
            :file-list="filesList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              文件支持docx、doc、pdf，文件大小100M以内，文件数量不能超过5份
            </div>
          </el-upload>
        </el-form-item>
      </div>
      <div
        class="plan-list-item"
        v-for="(item, index) in formData.contents"
        :key="index"
      >
        <el-form
          ref="subFormRef"
          label-position="top"
          :model="item"
          :rules="subRules"
          label-width="120px"
        >
          <div class="flex justify-between">
            <div style="color: #262626; font-size: 16px; font-weight: 700">
              子项{{ index + 1 }}
            </div>
            <el-popconfirm
              v-if="formData.contents.length > 1"
              :disabled="!canEdit"
              title="确定删除？"
              @confirm="handleDelPlanItem(index)"
            >
              <el-button slot="reference" type="danger" plain size="small"
                >删除</el-button
              >
            </el-popconfirm>
          </div>
          <div class="flex items-start flex-wrap">
            <el-form-item label="子项名称" prop="name">
              <el-input
                :disabled="!canEdit"
                class="w-240"
                size="small"
                v-model="item.name"
                placeholder="请输入名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="计划周期(起止)"
              prop="planDateTimeArr"
              class="ml-24"
            >
              <el-date-picker
                :disabled="!canEdit"
                size="small"
                v-model="item.planDateTimeArr"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="巡查人员" prop="operator" class="ml-24">
              <el-select
                :disabled="!canEdit"
                class="w-240"
                v-model="item.operator"
                multiple
                filterable
                remote
                :remote-method="searchUser"
                value-key="uid"
                placeholder="请输入关键词搜索用户"
              >
                <el-option
                  v-for="item in personnelList"
                  :key="item.uid"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="巡查范围" prop="scope">
            <div style="font-size: 12px; color: #00000099">暂无数据</div>
          </el-form-item>
          <el-form-item label="巡查路线(推荐)" prop="lineId">
            <el-select
              :disabled="!canEdit"
              class="w-240"
              v-model="item.lineName"
              filterable
              remote
              :remote-method="handleRemoteLineData"
              @focus="handleRemoteLineData('')"
              @change="(e) => handleChangeLine(item, e)"
              value-key="id"
              placeholder="请输入关键词搜索路线"
            >
              <el-option
                v-for="item in lineList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="巡查重点检查部位和内容" prop="remark">
            <el-input
              :disabled="!canEdit"
              size="small"
              type="textarea"
              :rows="3"
              v-model="item.remark"
              :maxlength="500"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div
        class="flex justify-start !mt-16"
        v-if="canEdit && formData.contents.length <= 50"
      >
        <el-button
          class="w-120"
          type="primary"
          @click="handleAddNewPlan"
          icon="el-icon-plus"
          >新增子项</el-button
        >
      </div>
    </el-form>
  </div>
</template>
<script>
import { listUser } from "@/api/management";
import {
  getProjectCheckingLineRoute,
  getRunProjectList,
  postProjectCheckingPlan,
  putProjectCheckingPlan,
  getProjectCheckingPlanDetails,
} from "@/api/dike";

import { uploadFileData } from "@/api/system/upload";

export default {
  props: {
    id: String,
    canEdit: Boolean,
  },

  data() {
    return {
      formData: {
        dikeName: "",
        dikeCode: "",
        dikeType: "",
        operator: "",
        cycleType: "1",
        reminderTime: "",
        files: [],
        otherConfig: {
          options: {},
          reminderDays: [],
          reminderWeeks: [],
        },
        contents: [
          {
            planDateTimeArr: [],
            startDate: "",
            endDate: "",
            operator: [],
            scope: "",
            lineId: "",
            remark: "",
            status: "0",
          },
        ],
      },
      rules: {
        dikeName: [
          { required: true, message: "请选择堤防", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择计划类型", trigger: "change" },
        ],
        cycleType: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
        "otherConfig.reminderDays": [
          { required: true, message: "请选择", trigger: "change" },
        ],
        "otherConfig.reminderWeeks": [
          { required: true, message: "请选择", trigger: "change" },
        ],
        reminderTime: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        frequency: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      subRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        planDateTimeArr: [
          { required: true, message: "请选择周期", trigger: "change" },
        ],
        operator: [
          { required: true, message: "请选择巡查人员", trigger: "change" },
        ],
        lineId: [{ required: true, message: "请选择路线", trigger: "change" }],
      },
      filesList: [],
      dikeList: [],
      projectTypeOptions: [],
      personnelList: [], // 人员列表
      lineList: [], // 线路列表
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.getDetail();
        }
      },
      immediate: true,
    },
  },
  created() {
    this.searchUser();
    this.getDicts("embankment_type").then((response) => {
      this.projectTypeOptions = response.data;
    });
  },
  methods: {
    getDetail() {
      getProjectCheckingPlanDetails(this.id).then((res) => {
        this.formData = res.data;
        this.formData.contents?.forEach((v) => {
          if (v.startDate && v.endDate) {
            v.planDateTimeArr = [v.startDate, v.endDate];
          }
        });
        this.filesList = res.data.files.map((item) => {
          return {
            name: item,
            url: item,
          };
        });
        this.handleRemoteLineData(res.data.name);
      });
    },
    handleChangeDike() {
      let res = this.dikeList.find(
        (v) => v.dikeName === this.formData.dikeName
      );
      this.formData.dikeCode = res.dikeCode;
      this.formData.dikeType = res.dikeType;
      this.formData.dikeName = res.dikeName;
      this.formData.dutyHolder = res.dutyHolders.find(
        (v) => v.dutyHolderType === "0"
      )?.name;
    },
    handleGetRemoteDikeMethod(query) {
      getRunProjectList({
        pageSize: 10,
        pageNum: 1,
        data: {
          dikeName: query,
        },
      }).then((res) => {
        if (res) {
          this.dikeList = res.records;
        }
      });
    },
    handleChangeLine(item, e) {
      let res = this.lineList.find((v) => v.name === e);
      item.lineId = res.id;
      item.lineName = res.name;
    },
    // 上传前
    beforeUpload(e) {
      console.log("beforeUpload >>>>>  ", e);
      const { name, size } = e;
      if (size > 100 * 1024 * 1024) {
        this.$message.warning("文件大小不能超过100M");
        return false;
      }
      if (!/\.(docx|doc|pdf)$/.test(name)) {
        this.$message.warning("文件格式不正确");
        return false;
      }
      if (this.formData.files?.length >= 5) {
        // this.$message.warning("最多上传5份");
        this.$message({
          message: "最多上传5份",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    handleUpload(e) {
      const { file } = e;
      let fData = new FormData();
      fData.append("file", file);
      uploadFileData(fData)
        .then((res) => {
          this.formData.files?.push(res.url);
        })
        .catch((err) => {
          console.log("err >>>>>  ", err);
        });
    },
    beforeRemove(file, fileList) {
      if (this.file) {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    },
    handleChangeRemindType() {
      this.formData.remindTime = "";
      this.formData.remindDay = [];
    },
    handleAddNewPlan() {
      if (this.formData.contents.length >= 50) {
        this.$message.warning("最多添加50个子项");
        return;
      }
      this.formData.contents.push({
        planDateTimeArr: [],
        startDate: "",
        endDate: "",
        operator: [],
        scope: "",
        lineId: "",
        remark: "",
        status: "0",
      });
    },
    handleDelPlanItem(index) {
      this.formData.contents.splice(index, 1);
    },
    // 搜索用户
    searchUser(e) {
      listUser({
        data: {
          timeView: {
            timeField: "create_time",
          },
        },
        cv: {
          name: "nickName",
          type: "like",
          value: e,
        },
        pageSize: 100,
        pageNum: 1,
      }).then((res) => {
        this.personnelList = res.records.map((item) => {
          return {
            name: item.nickName,
            uid: item.id,
          };
        });
      });
    },
    handleRemoteLineData(e) {
      getProjectCheckingLineRoute({
        data: {
          lineName: e,
        },
        pageNum: 1,
        pageSize: 10,
      }).then((res) => {
        this.lineList = res.records;
      });
    },
    submit(reset) {
      console.log("提交表单 >>>> ", this.formData);
      return new Promise((r, j) => {
        Promise.all([
          this.$refs.formRef.validate(),
          ...this.$refs.subFormRef.map((item) => item.validate()),
        ])
          .then((res) => {
            // 二次确认
            this.$confirm("确认提交吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.formData.contents.forEach((item) => {
                  item.startDate = item.planDateTimeArr[0]
                    ? item.planDateTimeArr[0] + " 00:00:00"
                    : "";
                  item.endDate = item.planDateTimeArr[1]
                    ? item.planDateTimeArr[1] + " 23:59:59"
                    : "";
                });
                (this.id ? putProjectCheckingPlan : postProjectCheckingPlan)({
                  id: this.id || null,
                  ...this.formData,
                })
                  .then((res) => {
                    this.$message.success("提交成功");
                    if (reset) {
                      this.reset();
                    }
                    r();
                  })
                  .catch(() => {
                    j();
                  });
              })
              .catch(() => {});
          })
          .catch(() => {
            j();
          });
      });
    },
    reset() {
      this.formData = {
        dikeName: "",
        dikeCode: "",
        dikeType: "",
        operator: "",
        cycleType: "1",
        reminderTime: "",
        files: [],
        otherConfig: {
          options: {},
          reminderDays: [],
          reminderWeeks: [],
        },
        contents: [
          {
            planDateTimeArr: [],
            startDate: "",
            endDate: "",
            operator: [],
            scope: "",
            lineId: "",
            remark: "",
          },
        ],
      };

      this.$refs.formRef.resetFields();
      if (this.$refs.subFormRef) {
        this.$refs.subFormRef.forEach((item) => {
          item.resetFields();
        });
      }
    },
  },
};
</script>
<style scoped lang="scss">
.detail-page {
  width: 100%;
  max-width: 1300px;
  padding: 16px;
  padding-bottom: 78px;
  border-radius: 6px;
  background-color: #fff;
  .form-row-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    border-left: 4px solid #36b29e;
    padding-left: 8px;
  }
  .w-100 {
    width: 100px !important;
  }
  .w-240 {
    width: 240px !important;
  }

  .plan-list-item {
    position: relative;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 16px;
    margin-top: 16px;
  }

  .del-btn {
    cursor: pointer;
    z-index: 1;
    width: 18px;
    font-size: 18px;
  }
}
</style>
<style lang="scss">
.detail-page {
  .custom-select-cycleType {
    .el-input__inner {
      border-radius: 4px 0 0 4px;
    }
  }
  .custom-select-date {
    .el-input__inner {
      border-radius: 0;
    }
  }
  .custom-time-piker {
    .el-input__inner {
      border-radius: 0 4px 4px 0;
    }
  }
}
.custom-select-date-popper {
  width: 202px !important;
  padding-left: 10px;
  .el-select-dropdown__list {
    display: flex;
    flex-wrap: wrap;
    .el-select-dropdown__item {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0;
      width: 42px;
      height: 32px;
      &.selected {
        &::after {
          display: none;
        }
      }
    }
  }
}
</style>
