<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form
        ref="ref_form"
        :inline="true"
        :model="fmData"
        :rules="dataRule"
        :disabled="formType === 'watch'"
        class="form"
      >
        <el-form-item
          label="服务类别	"
          prop="serviceCategoryKey"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-if="formType == 'add'"
            v-model="fmData.serviceCategoryKey"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div v-else>{{ fmData.serviceCategory || "--" }}</div>
        </el-form-item>

        <el-form-item
          label="项目名称"
          prop="serviceName"
          label-width="150px"
          style="display: block"
        >
          <el-input
            v-if="formType == 'add' || formType == 'edit'"
            class="item_width_1"
            maxlength="100"
            show-word-limit
            placeholder="请输入项目名称"
            v-model="fmData.serviceName"
          >
          </el-input>
          <div v-else>{{ fmData.serviceName || "--" }}</div>
        </el-form-item>

        <el-form-item
          label="服务内容"
          prop="serviceContent"
          label-width="150px"
          style="display: block"
        >
          <el-input
            v-if="formType == 'add' || formType == 'edit'"
            class="item_width_1"
            type="textarea"
            maxlength="1000"
            show-word-limit
            :rows="3"
            placeholder="请输入服务内容，不超过1000字"
            v-model="fmData.serviceContent"
          ></el-input>
          <div v-else>{{ fmData.serviceContent || "--" }}</div>
        </el-form-item>

        <el-form-item
          label="政策级别	"
          prop="policyLevel"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-if="formType == 'add' || formType == 'edit'"
            v-model="fmData.policyLevel"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div v-else>{{ fmData.policyLevelName || "--" }}</div>
        </el-form-item>

        <el-form-item
          label="政策依据"
          prop="policyGround"
          label-width="150px"
          style="display: block"
        >
          <el-input
            v-if="formType == 'add' || formType == 'edit'"
            class="item_width_1"
            type="textarea"
            maxlength="1000"
            show-word-limit
            :rows="3"
            placeholder="请输入政策依据，不超过1000字"
            v-model="fmData.policyGround"
          ></el-input>
          <div v-else>{{ fmData.policyGround || "--" }}</div>
        </el-form-item>

        <el-form-item
          label="图片/附件"
          label-width="150px"
          style="display: block"
          prop="attachmentList"
        >
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="{ customerId: customerId }"
            :show-file-list="true"
            :file-list="fmData.attachmentList"
            :on-preview="handleImgPreview"
            :on-success="handleImgSuccess"
            :on-remove="handleImgRemove"
            :on-exceed="handleImgExceed"
            :before-upload="beforeImgUpload"
            :limit="3"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <span style="color: #999"> 点击上传，支持图片、word、pdf格式</span>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <div class="div_btn resi-btns">
      <el-button size="small" @click="handleCancle">取 消</el-button>
      <el-button
        v-if="formType != 'watch'"
        type="primary"
        size="small"
        :disabled="btnDisable"
        @click="handleComfirm"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { requestPost } from "@/js/dai/request";
import formVltHelper from "dai-js/tools/formVltHelper";

export default {
  props: {
    formId: {
      type: String,
      default: "",
    },
    formType: {
      type: String,
      default: "info",
    },
  },

  data() {
    return {
      uploadUrl: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadqrcodeV2",
      customerId: localStorage.getItem("customerId"),

      btnDisable: false,

      fmData: {
        serviceCategoryKey: "",
        serviceName: "",
        serviceContent: "",
        policyGround: "",
        policyLevel: "",
        attachmentList: [],
      },

      levelOptions: [
        {
          value: "0",
          label: "市级",
        },
        {
          value: "1",
          label: "区级",
        },
        {
          value: "2",
          label: "街道级",
        },
      ],
      categoryOptions: [],
    };
  },
  components: {},
  computed: {
    dataRule() {
      return {
        serviceCategoryKey: [
          { required: true, message: "服务类别不能为空", trigger: "blur" },
        ],
        serviceName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        serviceContent: [
          { required: true, message: "服务内容不能为空", trigger: "blur" },
        ],
        // policyGround: [
        //   { required: true, message: "政策依据不能为空", trigger: "blur" },
        // ],
        // policyLevel: [
        //   { required: true, message: "政策级别不能为空", trigger: "blur" },
        // ],
      };
    },
  },
  watch: {},

  async mounted() {
    this.initForm();
  },

  methods: {
    async initForm() {
      this.getCategoryOpitons();
      if (this.formId && this.formType != "add") {
        this.getInfo();
      }
    },

    async getInfo() {
      const url = "/heart/icServiceProject/serviceProjectDetail";

      const params = {
        serviceProjectId: this.formId,
      };

      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.fmData = { ...this.fmData, ...data };
      } else {
        this.$message.error(msg);
      }
    },

    async getCategoryOpitons() {
      const url = "/sys/dict/data/dictlist";
      const params = {
        dictType: "ic_service_type",
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.categoryOptions = data || [];
      } else {
        this.$message.error(msg);
      }
    },

    beforeImgUpload(file) {
      console.log(file);
      const isLt1M = file.size / 1024 / 1024 < 10;
      const srcType = file.type;
      const format = file.name.split(".").pop();

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }
      if (
        srcType.indexOf("image") == -1 &&
        srcType.indexOf("video") == -1 &&
        ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"].indexOf(format) ==
          -1
      ) {
        this.$message.error("仅限图片、word和pdf文件!");
        return false;
      }
      return true;
    },

    handleImgSuccess(res, file, fileList) {
      console.log("handleImgSuccess", file);
      if (res.code === 0 && res.msg === "success") {
        let format = file.name.split(".").pop();
        let srcType = file.raw.type;
        let type = "file";
        console.log("==============================srcType: ", srcType);
        if (srcType.indexOf("image") != -1) {
          type = "image";
        } else if (srcType.indexOf("video") != -1) {
          type = "video";
        }
        this.fmData.attachmentList.push({
          format,
          name: file.name,
          size: file.size,
          type,
          url: res.data.url,
        });
        console.log(this.fmData.attachmentList);
      } else {
        this.$message.error(res.msg);
      }
    },

    handleImgPreview(file) {
      console.log(file);
      window.open(file.url || file.response.data.url);
    },

    handleImgRemove(file) {
      console.log("handleImgRemove", file);
      if (file.response) {
        let index = this.fmData.attachmentList.findIndex(
          (item) => item.url == file.response.data.url
        );
        this.fmData.attachmentList.splice(index, 1);
      } else if (file.url) {
        let index = this.fmData.attachmentList.findIndex(
          (item) => item.url == file.url
        );
        this.fmData.attachmentList.splice(index, 1);
      }
    },

    handleImgExceed() {
      this.$message({
        type: "warning",
        message: "文件数量最多不超过三个",
      });
    },

    watchImg(src) {
      window.open(src);
    },

    async handleComfirm() {
      this.btnDisable = true;
      setTimeout(() => {
        this.btnDisable = false;
      }, 10000);
      this.$refs["ref_form"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          this.btnDisable = false;
        } else {
          this.submit();
        }
      });
    },

    async submit() {
      let url = "";
      let params = { ...this.fmData };
      if (this.formType === "add") {
        url = "/heart/icServiceProject/serviceProjectAdd";
      } else {
        url = "/heart/icServiceProject/serviceProjectEdit";

        params.serviceProjectId = this.formId;
      }
      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        this.$emit("afterEdit");
        this.btnDisable = false;
      } else {
        this.btnDisable = false;
        this.$message.error(msg);
      }
    },

    handleCancle() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
.item_width_1 {
  width: 500px;
}
.item_width_2 {
  width: 400px;
}
.item_width_3 {
  margin-left: 10px;
  width: 200px;
}
.item_width_4 {
  width: 200px;
}

.div_map {
  margin-top: 10px;
}

.div_btn {
  // display: flex;
  // justify-content: flex-end;
}
.el-tabs {
  margin: 0 20px;
}
.el-upload__tip {
  color: rgb(155, 155, 155);
  margin: 0;
}
.form {
  margin-top: 30px;
}

.attachement-list {
}
</style>
