<!--  -->
<template>
  <div class="saveOftenSearch">
    <el-dialog
      title="添加常用搜索"
      :visible.sync="dialogVisible"
      width="480px"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      custom-class="save-often-search-dialog"
      append-to-body
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入"
            clear="true"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  import Emitter from '@/mixins/emitter'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    mixins: [Emitter],
    props: {
      fieldArray: {
        type: Array,
        default: () => [],
      },
      onlyOftenUsedKey: {
        type: String,
        default: '',
        required: true,
      },
    },
    data() {
      //这里存放数据
      return {
        dialogVisible: false,
        rules: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        },
        ruleForm: {
          name: '',
        },
        OftenUsedList: [],
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {},
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {},
    //方法集合
    methods: {
      showDialog() {
        if (!this.fieldArray.some((item) => item.value)) {
          this.$message.error(`请输入常用字段内容！`)
          return
        }
        this.dialogVisible = true
        Object.assign(this.ruleForm, {
          name: '',
        })
        this.$requestConfig.commonList(this.onlyOftenUsedKey).then((res) => {
          this.OftenUsedList = res
        })
      },
      save() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.OftenUsedList.length > 0) {
              try {
                this.OftenUsedList.forEach((item) => {
                  if (item.key == this.ruleForm.name) {
                    throw {
                      type: 'label',
                    }
                  }
                  let content = JSON.parse(item.content)
                  if (_.isEqual(content, this.fieldArray)) {
                    throw {
                      type: 'el-form-item__content',
                    }
                  }
                })
              } catch (e) {
                if (e.type == 'label') {
                  this.$message.error(`该常用搜索名称已存在,请修改!`)
                } else {
                  this.$message.error(`该常用搜索内容已在,请修改搜索条件!`)
                }
                return
              }
            }

            let params = {
              userId: this.$store.state.user.UsersAndDepartment.id,
              key: this.ruleForm.name,
              tableKey: this.onlyOftenUsedKey,
              content: JSON.stringify(this.fieldArray),
            }
            this.$requestConfig.commonSearch(params).then((res) => {
              if (res.state) {
                this.$message.success(`保存成功`)

                this.$parent.$parent.$parent.$parent.$emit(
                  'update-often-search'
                )
                this.dialogVisible = false
              } else {
                this.$message.error(`保存失败`)
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
    }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
<style lang="scss" scoped>
  //@import url(); 引入公共css类
  ::v-deep {
    .el-form-item {
      margin: 9px 0;
    }
  }
</style>
<style lang="scss">
  .save-often-search-dialog {
    .el-dialog__body {
      padding: 15px 22px 15px 24px;
      .el-form-item {
        display: flex;
        .el-form-item__content {
          flex: 1;
        }
      }
    }
    .el-dialog__footer {
      padding: 16px 24px;
      .el-button + .el-button {
        margin-left: 16px;
      }
    }
  }
</style>
