<template>
  <div>
    <el-drawer
      :title="dialogTitle"
      :before-close="handleClose"
      :visible.sync="addRuleDialogVisible"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      @close="closeDrawer"
      size="50%"
      class="rules-add-dialog"
    >
      <div class="demo-drawer__content">
        <el-form
          :model="addRulesForm"
          :rules="formRules"
          ref="addRulesForm"
          label-position="right"
          label-width="120px"
        >
          <el-form-item
            label="所属一级分类："
            :label-width="formLabelWidth"
            prop="firstId"
          >
            <el-select
              v-model="addRulesForm.firstId"
              placeholder="请选择所属一级分类"
              @change="selectChange"
            >
              <el-option
                v-for="(item, index) in firstItemList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="所属二级分类："
            :label-width="formLabelWidth"
            prop="secondId"
          >
            <el-select
              v-model="addRulesForm.secondId"
              placeholder="请选择所属二级分类"
              @change="$forceUpdate()"
            >
              <el-option
                v-for="(item, index) in secondItemList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="制度名称："
            :label-width="formLabelWidth"
            prop="docName"
          >
            <el-input
              v-model="addRulesForm.docName"
              placeholder="请输入制度名称"
              style="width: 360px"
              maxlength="20"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item
            label="上传文档："
            :label-width="formLabelWidth"
            prop="docUrl"
          >
            <el-upload
              :action="putFile"
              class="rules-upload-file"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :show-file-list="true"
              :on-success="handleFileSuccess"
              :before-upload="beforeFileUpload"
              :limit="1"
              accept=".pdf, .doc, .docx, .xls, .xlsx"
            >
              <el-button size="small" type="text">请选择文档</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上传图片："
            :label-width="formLabelWidth"
            prop="docImage"
          >
            <el-upload
              :action="putFile"
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
             
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-dialog
              :visible.sync="viewImgDialogVisible"
              append-to-body
              width="50%"
              class="addRules-view-dialog"
            >
              <img width="100%" height="100%" :src="imageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item
            label="状态："
            :label-width="formLabelWidth"
            prop="status"
          >
            <el-radio-group
              v-model="addRulesForm.status"
              @change="changeStatus"
            >
              <el-radio :label="0">显示</el-radio>
              <el-radio :label="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="addRuleDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  ruleGetTypeList,
  addRule,
  editRule,
  getRuleDetailInfo,
} from "@/api/manage/rules";

import { putFile } from "@/api/resource/oss";

export default {
  data() {
    return {
      addRuleDialogVisible: false,
      firstItemList: [],
      secondItemList: [],
      fileList: [],
      putFile,
      imageUrl: "",
      parentData: {},
      operateType: "",
      dialogTitle: "",
      addRulesForm: {
        firstId: "",
        secondId: "",
        docName: "",
        docUrl: "",
        docImage: "",
        status: 0,
      },
      query: {},
 
      formRules: {
        firstId: [
          {
            required: true,
            message: "请选择一级分类",
            trigger: "blur",
          },
        ],
        /* secondId: [
          {
            required: true,
            message: "请选择二级分类",
            trigger: "blur",
          },
        ],*/
        docName: [
          {
            required: true,
            message: "请输入制度名称",
            trigger: "blur",
          },
        ],
        docUrl: [
          {
            required: true,
            message: "请上传制度文档",
            trigger: "blur",
          },
        ],
        docImage: [
          {
            required: true,
            message: "请上传制度封面",
            trigger: "blur",
          },
        ],
      },
    };
  },
  
  methods: {
    openDrawer() {
      this.addRuleDialogVisible = true;
      this.firstItemList = [];
      ruleGetTypeList(0).then((res) => {
        this.firstItemList = res.data.data;
      });
    },
    selectChange(val) {
      this.secondItemList = [];
      this.addRulesForm.secondId = "";
      ruleGetTypeList(val).then((res) => {
        this.secondItemList = res.data.data;
        /* if(this.secondItemList.length==0){/**一级分类下，二级分类为空时，默认显示“无” 
          this.secondItemList=[
            {
              id:-1,
              name:"无"
            },
          ]
        }*/
      });
    },

    closeDrawer() {
      this.addRulesForm = {};
      this.imageUrl = "";
      this.docUrl = "";
      this.fileList = [];
      this.firstItemList = [];
      this.secondItemList = [];
    },

    /**图片上传 */

   
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$set(this.addRulesForm, "docImage", res.data.link);
    },

    
    uploadImgSuccess(res) {
      this.$set(this.addRulesForm, "docImage", res.data.link);
    },
   
    beforeAvatarUpload(file) {
      const isJPG =
        ["image/png", "image/jpeg", "image/svg+xml", "image/gif"].indexOf(
          file.type
        ) != -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片格式不正确");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /**图片上传 */

    /**文件上传 */
    handleExceed() {
      this.$message.warning("最多只能上传一个文件");
    },
    handleRemove() {
      this.addRulesForm.docUrl = "";
    },
    handleFileSuccess(res) {
      this.$set(this.addRulesForm, "docUrl", res.data.link);
    },
    beforeFileUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["pdf", "doc", "docx", "xls", "xlsx"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是 pdf、doc、docx、xls、xlsx格式");
        return false;
      }
    },
    /**文件上传 */

    /**提交表单 */
    onSubmit() {
      this.$refs.addRulesForm.validate((valid) => {
        if (valid) {
          if (this.operateType == "add") {
            let secondid = this.addRulesForm.secondId;
            /*  if(secondid==-1){
              secondid="";
            }*/
            addRule(
              this.addRulesForm.firstId,
              secondid,
              this.addRulesForm.docName,
              this.addRulesForm.docUrl,
              this.addRulesForm.docImage,
              this.addRulesForm.status
            ).then(() => {
              this.$message.success("添加成功");
              this.$emit("success");
              this.addRuleDialogVisible = false;
            });
          } else if (this.operateType == "edit") {
            let firId =
              this.addRulesForm.firstId == this.parentData.categoryOne
                ? this.parentData.firstId
                : this.addRulesForm.firstId;
            let secId =
              this.addRulesForm.secondId == this.parentData.categoryTwo
                ? this.parentData.secondId
                : this.addRulesForm.secondId;
            /* if(secId==-1){
              secId="";
            }*/
            editRule(
              this.parentData.id,
              firId,
              secId,
              this.addRulesForm.docName,
              this.addRulesForm.docUrl,
              this.addRulesForm.docImage,
              this.addRulesForm.status
            ).then(() => {
              this.$message.success("修改成功");
              this.$emit("success");
              this.addRuleDialogVisible = false;
            });
          }
        }
      });
      /*
       */
    },
    getRuleInfo() {
      this.addRulesForm.firstId = this.parentData.categoryOne;
      this.addRulesForm.secondId = this.parentData.categoryTwo;
      getRuleDetailInfo(this.parentData.id).then((res) => {
        const data = res.data.data;
        // this.addRulesForm.docName = data.docName;
        this.$set(this.addRulesForm, "docName", data.docName);
        this.addRulesForm.docUrl = data.docUrl;
        this.addRulesForm.docImage = data.docImage;
        //this.addRulesForm.status = data.status;
        this.$set(this.addRulesForm, "status", data.status);

        this.imageUrl = data.docImage;
        this.whetherShowImg = true;
      });
    },
    changeStatus(val) {
      this.$set(this.addRulesForm, "status", val);
    },
    open(data, type) {
      this.parentData = data;
      this.operateType = type;
      this.firstItemList = [];
      ruleGetTypeList(0).then((res) => {
        this.firstItemList = res.data.data;
      });
      this.addRuleDialogVisible = true;
      if (this.operateType == "edit") {
        this.dialogTitle = "查看制度";
        /**1、获取form的值，显示在页面上
         * 2、给两个select的option赋值 */
        this.getRuleInfo();
      } else {
        this.dialogTitle = "新增制度";

        this.addRulesForm = {
          status: 0,
        };
      }
    },
  },
};
</script>

<style scoped>
.rules-img-upload {
  list-style: none;
  width: 180px;
  height: 180px;
  position: relative;
}
.delete-img {
  display: block;
  position: absolute;
  width: 180px;
  height: 40px;
  line-height: 40px;
  left: 0px;
  top: 140px;
  background: rgba(59, 60, 61, 0.5);
  z-index: 999;
  cursor: pointer;
  text-align: right;
}
.rules-img-upload .delete-img .el-icon-delete {
float: left;
  display: block;
  font-size: 24px;
  color: white;
  margin-left: 10px;
}
.rules-img-upload .delete-img .el-icon-zoom-in {
  float: right;
  display: block;
  font-size: 24px;
  color: white;
  margin-right: 10px;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.addRules-view-dialog /deep/ .el-dialog {
  height: 80%;
}

.rules-add-dialog .el-form-item {
    margin-bottom: 22px!important;
}
.rules-add-dialog  /deep/  .el-form-item__label{
  font-size: 14px;
}
 .rules-add-dialog  .el-input{
  font-size: 14px;
}
 .rules-add-dialog /deep/.el-input--suffix .el-input__inner{
  font-size: 14px;
}
</style>
