<template>
  <!-- 主容器 -->
  <div class="addEdit-block">
    <!-- 表单组件 -->
    <el-form
      class="detail-form-content"
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="80px"
      :style="{backgroundColor:addEditForm.addEditBoxColor}"
    >
      <!-- 表单项布局行 -->
      <el-row>
        <!-- 占据12列（半屏） -->
        <el-col :span="12">
          <!-- 标题输入项，非查看模式显示可编辑框 -->
          <el-form-item class="input" v-if="type!='info'" label="标题" prop="title">
            <el-input v-model="ruleForm.title"
              placeholder="标题" clearable :readonly="ro.title"></el-input>
          </el-form-item>
          <!-- 查看模式下显示只读输入框 -->
          <div v-else>
            <el-form-item class="input" label="标题" prop="title">
              <el-input v-model="ruleForm.title"
                placeholder="标题" readonly></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 图片上传 -->
      <el-row>
        <el-col :span="24">
          <!-- 非查看模式下显示文件上传控件 -->
          <el-form-item class="upload" v-if="type!='info' && !ro.picture" label="图片" prop="picture">
            <file-upload
              tip="点击上传图片"
              action="file/upload"
              :limit="3"
              :multiple="true"
              :fileUrls="ruleForm.picture?ruleForm.picture:''"
              @change="pictureUploadChange"
            ></file-upload>
          </el-form-item>
          <!-- 查看模式下显示已上传图片 -->
          <div v-else>
            <el-form-item v-if="ruleForm.picture" label="图片" prop="picture">
              <!-- 显示多张图片 -->
              <img style="margin-right:20px;" v-bind:key="index" v-for="(item,index) in ruleForm.picture.split(',')" :src="item" width="100" height="100">
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 简介 -->
      <el-row>
        <el-col :span="24">
          <el-form-item class="textarea" v-if="type != 'info'" label="简介" prop="introduction">
            <el-input
              style="min-width: 200px; max-width: 600px;"
              type="textarea"
              :rows="8"
              placeholder="简介"
              v-model="ruleForm.introduction">
            </el-input>
          </el-form-item>
          <div v-else>
            <el-form-item v-if="ruleForm.introduction" label="简介" prop="introduction">
              <span>{{ ruleForm.introduction }}</span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 内容 -->
      <el-row>
        <el-col :span="24">
          <el-form-item v-if="type != 'info'" label="内容" prop="content">
            <editor
              style="min-width: 200px; max-width: 600px;"
              v-model="ruleForm.content"
              class="editor"
              action="file/upload">
            </editor>
          </el-form-item>
          <div v-else>
            <el-form-item v-if="ruleForm.content" label="内容" prop="content">
              <span v-html="ruleForm.content"></span>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 提交按钮区域 -->
      <el-form-item class="btn">
        <!-- 非查看模式下显示提交和取消按钮 -->
        <el-button v-if="type != 'info'" type="primary" class="btn-success" @click="onSubmit">提交</el-button>
        <el-button v-if="type != 'info'" class="btn-close" @click="back()">取消</el-button>
        <!-- 查看模式下显示返回按钮 -->
        <el-button v-if="type == 'info'" class="btn-close" @click="back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 导入验证工具函数：数字、整数、邮箱、电话、手机号、URL、身份证校验
import { isNumber, isIntNumer, isEmail, isPhone, isMobile, isURL, checkIdCard } from "@/utils/validate";

export default {
  data() {
    let self = this;

    // 身份证格式校验
    var validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!checkIdCard(value)) {
        callback(new Error("请输入正确的身份证号码"));
      } else {
        callback();
      }
    };

    // URL格式校验
    var validateUrl = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isURL(value)) {
        callback(new Error("请输入正确的URL地址"));
      } else {
        callback();
      }
    };

    // 手机号格式校验
    var validateMobile = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isMobile(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    // 固定电话格式校验
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isPhone(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    };

    // 邮箱格式校验
    var validateEmail = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isEmail(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    };

    // 数字格式校验
    var validateNumber = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isNumber(value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };

    // 整数格式校验
    var validateIntNumber = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!isIntNumer(value)) {
        callback(new Error("请输入整数"));
      } else {
        callback();
      }
    };

    return {
      // 页面样式配置对象
      addEditForm: {
        "btnSaveFontColor": "#fff",
        "selectFontSize": "14px",
        "btnCancelBorderColor": "rgba(152, 129, 129, 1)",
        "inputBorderRadius": "22px",
        "inputFontSize": "14px",
        "textareaBgColor": "#fff",
        "btnSaveFontSize": "14px",
        "textareaBorderRadius": "22px",
        "uploadBgColor": "#fff",
        "textareaBorderStyle": "solid",
        "btnCancelWidth": "88px",
        "textareaHeight": "120px",
        "dateBgColor": "#fff",
        "btnSaveBorderRadius": "22px",
        "uploadLableFontSize": "14px",
        "textareaBorderWidth": "1px",
        "inputLableColor": "#606266",
        "addEditBoxColor": "rgba(210, 194, 194, 0.29)",
        "dateIconFontSize": "14px",
        "btnSaveBgColor": "#409EFF",
        "uploadIconFontColor": "#8c939d",
        "textareaBorderColor": "rgba(152, 129, 129, 1)",
        "btnCancelBgColor": "rgba(143, 222, 143, 1)",
        "selectLableColor": "#606266",
        "btnSaveBorderStyle": "solid",
        "dateBorderWidth": "1px",
        "dateLableFontSize": "14px",
        "dateBorderRadius": "22px",
        "btnCancelBorderStyle": "solid",
        "selectLableFontSize": "14px",
        "selectBorderStyle": "solid",
        "selectIconFontColor": "#C0C4CC",
        "btnCancelHeight": "44px",
        "inputHeight": "40px",
        "btnCancelFontColor": "#606266",
        "dateBorderColor": "rgba(152, 129, 129, 1)",
        "dateIconFontColor": "#C0C4CC",
        "uploadBorderStyle": "solid",
        "dateBorderStyle": "solid",
        "dateLableColor": "#606266",
        "dateFontSize": "14px",
        "inputBorderWidth": "1px",
        "uploadIconFontSize": "28px",
        "selectHeight": "40px",
        "inputFontColor": "#606266",
        "uploadHeight": "148px",
        "textareaLableColor": "#606266",
        "textareaLableFontSize": "14px",
        "btnCancelFontSize": "14px",
        "inputBorderStyle": "solid",
        "btnCancelBorderRadius": "22px",
        "inputBgColor": "rgba(252, 250, 250, 1)",
        "inputLableFontSize": "14px",
        "uploadLableColor": "#606266",
        "uploadBorderRadius": "22px",
        "btnSaveHeight": "44px",
        "selectBgColor": "#fff",
        "btnSaveWidth": "88px",
        "selectIconFontSize": "14px",
        "dateHeight": "40px",
        "selectBorderColor": "rgba(152, 129, 129, 1)",
        "inputBorderColor": "rgba(152, 129, 129, 1)",
        "uploadBorderColor": "rgba(152, 129, 129, 1)",
        "textareaFontColor": "#606266",
        "selectBorderWidth": "1px",
        "dateFontColor": "#606266",
        "btnCancelBorderWidth": "1px",
        "uploadBorderWidth": "1px",
        "textareaFontSize": "14px",
        "selectBorderRadius": "22px",
        "selectFontColor": "#606266",
        "btnSaveBorderColor": "#409EFF",
        "btnSaveBorderWidth": "1px"
      },
      id: '',         // 当前操作数据ID
      type: '',       // 操作类型（新增、编辑、详情）
      ro: {           // 只读字段控制
        title: false,
        introduction: false,
        picture: false,
        content: false,
      },
      ruleForm: {     // 表单绑定数据模型
        title: '',
        introduction: '',
        picture: '',
        content: '',
      },
      rules: {        // 表单验证规则
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        introduction: [],
        picture: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  props: ["parent"], // 接收父组件传递的数据

  computed: {
    // 计算属性
  },

  created() {
    // 组件创建时调用样式初始化方法
    this.addEditStyleChange();
    this.addEditUploadStyleChange();
  },

  methods: {
    // 下载文件
    download(file){
      window.open(`${file}`);
    },

    // 初始化方法
    init(id, type) {
      if (id) {
        this.id = id;
        this.type = type;
      }

      // 如果是查看详情或跨表操作，则加载对应数据
      if(this.type === 'info' || this.type === 'else'){
        this.info(id);
      } else if(this.type === 'cross'){
        var obj = this.$storage.getObj('crossObj');
        for (var o in obj){
          if(o==='title'){
            this.ruleForm.title = obj[o];
            this.ro.title = true;
            continue;
          }
          if(o==='introduction'){
            this.ruleForm.introduction = obj[o];
            this.ro.introduction = true;
            continue;
          }
          if(o==='picture'){
            this.ruleForm.picture = obj[o];
            this.ro.picture = true;
            continue;
          }
          if(o==='content'){
            this.ruleForm.content = obj[o];
            this.ro.content = true;
            continue;
          }
        }
      }
    },

    // 获取详情信息
    info(id) {
      this.$http({
        url: `news/info/${id}`,
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.ruleForm = data.data;
        } else {
          this.$message.error(data.msg);
        }
      });
    },

    // 提交表单
    onSubmit() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: `news/${!this.ruleForm.id ? "save" : "update"}`,
            method: "post",
            data: this.ruleForm
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.parent.showFlag = true;
                  this.parent.addOrUpdateFlag = false;
                  this.parent.newsCrossAddOrUpdateFlag = false;
                  this.parent.search();
                  this.parent.contentStyleChange();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },

    // 获取UUID
    getUUID () {
      return new Date().getTime();
    },

    // 返回上一页
    back() {
      this.parent.showFlag = true;
      this.parent.addOrUpdateFlag = false;
      this.parent.newsCrossAddOrUpdateFlag = false;
      this.parent.contentStyleChange();
    },

    // 图片上传回调
    pictureUploadChange(fileUrls) {
      this.ruleForm.picture = fileUrls;
      this.addEditUploadStyleChange();
    },

    // 动态设置表单元素样式
    addEditStyleChange() {
      this.$nextTick(()=>{
        // input
        document.querySelectorAll('.addEdit-block .input .el-input__inner').forEach(el=>{
          el.style.height = this.addEditForm.inputHeight;
          el.style.color = this.addEditForm.inputFontColor;
          el.style.fontSize = this.addEditForm.inputFontSize;
          el.style.borderWidth = this.addEditForm.inputBorderWidth;
          el.style.borderStyle = this.addEditForm.inputBorderStyle;
          el.style.borderColor = this.addEditForm.inputBorderColor;
          el.style.borderRadius = this.addEditForm.inputBorderRadius;
          el.style.backgroundColor = this.addEditForm.inputBgColor;
        });

        document.querySelectorAll('.addEdit-block .input .el-form-item__label').forEach(el=>{
          el.style.lineHeight = this.addEditForm.inputHeight;
          el.style.color = this.addEditForm.inputLableColor;
          el.style.fontSize = this.addEditForm.inputLableFontSize;
        });

        // select
        document.querySelectorAll('.addEdit-block .select .el-input__inner').forEach(el=>{
          el.style.height = this.addEditForm.selectHeight;
          el.style.color = this.addEditForm.selectFontColor;
          el.style.fontSize = this.addEditForm.selectFontSize;
          el.style.borderWidth = this.addEditForm.selectBorderWidth;
          el.style.borderStyle = this.addEditForm.selectBorderStyle;
          el.style.borderColor = this.addEditForm.selectBorderColor;
          el.style.borderRadius = this.addEditForm.selectBorderRadius;
          el.style.backgroundColor = this.addEditForm.selectBgColor;
        });

        document.querySelectorAll('.addEdit-block .select .el-form-item__label').forEach(el=>{
          el.style.lineHeight = this.addEditForm.selectHeight;
          el.style.color = this.addEditForm.selectLableColor;
          el.style.fontSize = this.addEditForm.selectLableFontSize;
        });

        document.querySelectorAll('.addEdit-block .select .el-select__caret').forEach(el=>{
          el.style.color = this.addEditForm.selectIconFontColor;
          el.style.fontSize = this.addEditForm.selectIconFontSize;
        });

        // date
        document.querySelectorAll('.addEdit-block .date .el-input__inner').forEach(el=>{
          el.style.height = this.addEditForm.dateHeight;
          el.style.color = this.addEditForm.dateFontColor;
          el.style.fontSize = this.addEditForm.dateFontSize;
          el.style.borderWidth = this.addEditForm.dateBorderWidth;
          el.style.borderStyle = this.addEditForm.dateBorderStyle;
          el.style.borderColor = this.addEditForm.dateBorderColor;
          el.style.borderRadius = this.addEditForm.dateBorderRadius;
          el.style.backgroundColor = this.addEditForm.dateBgColor;
        });

        document.querySelectorAll('.addEdit-block .date .el-form-item__label').forEach(el=>{
          el.style.lineHeight = this.addEditForm.dateHeight;
          el.style.color = this.addEditForm.dateLableColor;
          el.style.fontSize = this.addEditForm.dateLableFontSize;
        });

        document.querySelectorAll('.addEdit-block .date .el-input__icon').forEach(el=>{
          el.style.color = this.addEditForm.dateIconFontColor;
          el.style.fontSize = this.addEditForm.dateIconFontSize;
          el.style.lineHeight = this.addEditForm.dateHeight;
        });

        // upload
        let iconLineHeight = parseInt(this.addEditForm.uploadHeight) - parseInt(this.addEditForm.uploadBorderWidth) * 2 + 'px';
        document.querySelectorAll('.addEdit-block .upload .el-upload--picture-card').forEach(el=>{
          el.style.width = this.addEditForm.uploadHeight;
          el.style.height = this.addEditForm.uploadHeight;
          el.style.borderWidth = this.addEditForm.uploadBorderWidth;
          el.style.borderStyle = this.addEditForm.uploadBorderStyle;
          el.style.borderColor = this.addEditForm.uploadBorderColor;
          el.style.borderRadius = this.addEditForm.uploadBorderRadius;
          el.style.backgroundColor = this.addEditForm.uploadBgColor;
        });

        document.querySelectorAll('.addEdit-block .upload .el-form-item__label').forEach(el=>{
          el.style.lineHeight = this.addEditForm.uploadHeight;
          el.style.color = this.addEditForm.uploadLableColor;
          el.style.fontSize = this.addEditForm.uploadLableFontSize;
        });

        document.querySelectorAll('.addEdit-block .upload .el-icon-plus').forEach(el=>{
          el.style.color = this.addEditForm.uploadIconFontColor;
          el.style.fontSize = this.addEditForm.uploadIconFontSize;
          el.style.lineHeight = iconLineHeight;
          el.style.display = 'block';
        });

        // textarea
        document.querySelectorAll('.addEdit-block .textarea .el-textarea__inner').forEach(el=>{
          el.style.height = this.addEditForm.textareaHeight;
          el.style.color = this.addEditForm.textareaFontColor;
          el.style.fontSize = this.addEditForm.textareaFontSize;
          el.style.borderWidth = this.addEditForm.textareaBorderWidth;
          el.style.borderStyle = this.addEditForm.textareaBorderStyle;
          el.style.borderColor = this.addEditForm.textareaBorderColor;
          el.style.borderRadius = this.addEditForm.textareaBorderRadius;
          el.style.backgroundColor = this.addEditForm.textareaBgColor;
        });

        document.querySelectorAll('.addEdit-block .textarea .el-form-item__label').forEach(el=>{
          el.style.color = this.addEditForm.textareaLableColor;
          el.style.fontSize = this.addEditForm.textareaLableFontSize;
        });

        // 保存按钮
        document.querySelectorAll('.addEdit-block .btn .btn-success').forEach(el=>{
          el.style.width = this.addEditForm.btnSaveWidth;
          el.style.height = this.addEditForm.btnSaveHeight;
          el.style.color = this.addEditForm.btnSaveFontColor;
          el.style.fontSize = this.addEditForm.btnSaveFontSize;
          el.style.borderWidth = this.addEditForm.btnSaveBorderWidth;
          el.style.borderStyle = this.addEditForm.btnSaveBorderStyle;
          el.style.borderColor = this.addEditForm.btnSaveBorderColor;
          el.style.borderRadius = this.addEditForm.btnSaveBorderRadius;
          el.style.backgroundColor = this.addEditForm.btnSaveBgColor;
        });

        // 取消按钮
        document.querySelectorAll('.addEdit-block .btn .btn-close').forEach(el=>{
          el.style.width = this.addEditForm.btnCancelWidth;
          el.style.height = this.addEditForm.btnCancelHeight;
          el.style.color = this.addEditForm.btnCancelFontColor;
          el.style.fontSize = this.addEditForm.btnCancelFontSize;
          el.style.borderWidth = this.addEditForm.btnCancelBorderWidth;
          el.style.borderStyle = this.addEditForm.btnCancelBorderStyle;
          el.style.borderColor = this.addEditForm.btnCancelBorderColor;
          el.style.borderRadius = this.addEditForm.btnCancelBorderRadius;
          el.style.backgroundColor = this.addEditForm.btnCancelBgColor;
        });
      });
    },

    // 上传区域样式调整
    addEditUploadStyleChange() {
      this.$nextTick(()=>{
        document.querySelectorAll('.addEdit-block .upload .el-upload-list--picture-card .el-upload-list__item').forEach(el=>{
          el.style.width = this.addEditForm.uploadHeight;
          el.style.height = this.addEditForm.uploadHeight;
          el.style.borderWidth = this.addEditForm.uploadBorderWidth;
          el.style.borderStyle = this.addEditForm.uploadBorderStyle;
          el.style.borderColor = this.addEditForm.uploadBorderColor;
          el.style.borderRadius = this.addEditForm.uploadBorderRadius;
          el.style.backgroundColor = this.addEditForm.uploadBgColor;
        });
      });
    }
  }
};
</script>

<style lang="scss">
.editor{
  height: 500px;

  & /deep/ .ql-container {
    height: 310px;
  }
}
.amap-wrapper {
  width: 100%;
  height: 500px;
}
.search-box {
  position: absolute;
}
.addEdit-block {
  margin: -10px;
}
.detail-form-content {
  padding: 12px;
}
.btn .el-button {
  padding: 0;
}
</style>
