<template>
  <div>
    <el-dialog :title="isEdit && !readOnly ? '编辑群发消息' : '群发信息'" :visible.sync="show" width="680px" @closed="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="选择企业" prop="qfxxEnterpriseId">
          <el-select v-model="form.qfxxEnterpriseId" @change="onChangeEnterprise" :disabled="isEdit || readOnly">
            <el-option v-for="el in entepriseList" :key="el.wxEnterpriseId" :value="el.wxEnterpriseId" :label="el.corpName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务标题" prop="title">
          <template slot="label">
            <span>任务标题</span>
            <el-tooltip open-delay="200" placement="top">
              <i style="cursor:pointer;color:#909399;font-size:14px;" class="iconfont icon-xinxixianshi"></i>
              <div slot="content" style="width:376px;line-height: 22px;">计划创建后编辑任务标题，历史创建任务的标题不会更新，新下发任务按编辑后标题展示</div>
            </el-tooltip>
          </template>
          <el-input show-word-limit v-model.trim="form.title" :maxlength="20" :disabled="readOnly"></el-input>
        </el-form-item>
        <el-form-item label="任务描述" prop="remark">
          <template slot="label">
            <span>任务描述</span>
            <el-tooltip open-delay="200" placement="top">
              <i style="cursor:pointer;color:#909399;font-size:14px;" class="iconfont icon-xinxixianshi"></i>
              <div slot="content" style="width:376px;line-height: 22px;">计划创建后编辑任务描述，历史创建任务的描述按编辑后内容展示，新下发任务按编辑后内容展示</div>
            </el-tooltip>
          </template>
          <el-input class="task-desc" type="textarea" show-word-limit v-model="form.remark" :rows="4" :maxlength="200" resize="none" :disabled="readOnly"></el-input>
        </el-form-item>
        <el-form-item label="任务逾期判定" prop="expireDays">
          <el-input-number v-model="form.expireDays" :min="0" controls-position="right" :disabled="readOnly"></el-input-number>
          <span>天之后</span>
        </el-form-item>
        <el-form-item label="添加群发内容" prop="">
          <template slot="label">
            <span>添加群发内容</span>
            <el-tooltip open-delay="200" placement="top">
              <i style="cursor:pointer;color:#909399;font-size:14px;" class="iconfont icon-xinxixianshi"></i>
              <div slot="content" style="width:376px;line-height: 22px;">计划创建后编辑添加群发内容，历史创建群发内容不会更新，新下发任务按编辑后内容展示</div>
            </el-tooltip>
          </template>
          <div style="font-size:12px;color:#6B6D71;margin-bottom:10px">建议以文本+其他类型组合创建群发内容；文本内容最多只能添加 1 个</div>
          <div style="margin-bottom:16px;display:flex;flex-wrap:wrap;margin-top:12px">
            <material-item class="card-item" v-for="item in materials" :key="item.relation_id" :item="item" @delete="onDeleteMaterial" :read-only="readOnly"></material-item>
            <div v-show="materials.length < 3 && !readOnly" class="chat-item card-item" @click="openMaterialDialog">
              <i class="el-icon-plus"></i>
              <span class="add-text">添加素材 (最多3个)</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button style="width:74px" @click="close">取消</el-button>
        <el-button style="width:74px" type="primary" @click="addItem">确定</el-button>
      </template>
    </el-dialog>
    <dm-material :visible.sync="materialVisible" :types="[1, 2, 3, 4, 6]" @select="onSelectMaterial" :wx-enterprise-id="this.form.qfxxEnterpriseId" projectName="marketing" :material-ids="materials.map(el => el.relation_id)" :disableTypes="disableTypes"></dm-material>
  </div>
</template>

<script>
import { getEntepriseList } from '../assets/api';
import MaterialItem from './material-item';

export default {
  name: 'lib-qfxx',
  props: {
    item: {
      type: Object,
      default() {
        return {};
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  components: {
    MaterialItem
  },
  data() {
    return {
      form: {
        qfxxEnterpriseId: '',
        qfxxEnterpriseName: '',
        remark: '',
        title: '',
        expireDays: 0,
        chatContent: null
      },
      rules: {
        qfxxEnterpriseId: { required: true, message: '请选择企业', trigger: 'change' },
        title: { required: true, message: '请填写任务标题', trigger: 'blur' },
        remark: { required: true, message: '请填写任务描述', trigger: 'blur' },
        expireDays: { required: true, message: '请填写', trigger: 'blur' }
      },
      entepriseList: [],
      isEdit: false,
      ecmMarketingTypeRelationId: '',
      materials: [],
      materialVisible: false
    };
  },
  created() {
    this.getEntepriseList();
  },
  methods: {
    openMaterialDialog() {
      if (!this.form.qfxxEnterpriseId) {
        return this.$message.warning('请选择企业');
      }
      this.materialVisible = true;
    },
    close() {
      this.form = {
        qfxxEnterpriseId: '',
        qfxxEnterpriseName: '',
        remark: '',
        title: '',
        expireDays: 0,
        chatContent: null
      };
      this.ecmMarketingTypeRelationId = '';
      this.materials = [];
      this.$refs.form.resetFields();
      this.$emit('update:show', false);
    },
    async addItem() {
      const valid = await this.$refs.form.validate();
      if (!valid) return;
      let qfxx = { ...this.form };
      if (this.materials.length == 0) {
        this.$message.warning('请添加群发内容');
        return;
      } else if (this.materials.every(el => el.type != 1)) {
        this.$message.warning('请添加一条文本内容');
        return;
      }
      delete qfxx.title;
      qfxx.chatContent = JSON.stringify(this.materials.map(el => ({ relation_id: el.relation_id })));
      this.$emit('sendItem', { title: this.form.title, qfxx, comName: 'qfxx', ecmMarketingTypeRelationId: this.ecmMarketingTypeRelationId });
      this.close();
    },
    getEntepriseList() {
      getEntepriseList()
        .then(res => {
          if (res.errorCode === 0) {
            this.entepriseList = res.result || [];
          } else {
            this.$message({ message: res.message, type: 'error' });
          }
        })
        .catch(err => {
          this.$message({ message: err.data.message, type: 'error' });
        });
    },
    onChangeEnterprise(v) {
      let item = this.entepriseList.find(el => el.wxEnterpriseId == v);
      this.materials = [];
      if (item) {
        this.form.qfxxEnterpriseName = item.corpName;
      } else {
        this.form.qfxxEnterpriseName = '';
      }
    },
    onDeleteMaterial(id) {
      this.materials = this.materials.filter(el => el.relation_id != id);
    },
    onSelectMaterial(item) {
      this.materials.push({
        type: item.materialType,
        relation_id: item.materialId,
        title: item.materialTitle,
        content: item.materialContent || item.link,
        img: item.imgUrl
      });
    }
  },
  computed: {
    disableTypes() {
      if (this.materials.some(el => el.type == 1)) {
        return [1];
      } else {
        return [];
      }
    }
  },
  watch: {
    show: {
      handler() {
        if (Object.keys(this.item).length > 0) {
          this.isEdit = true;
          for (let key in this.form) {
            if (this.item.qfxx[key] !== undefined) {
              this.form[key] = this.item.qfxx[key];
            }
          }
          if (this.item.qfxx && this.item.qfxx.chatContent) {
            this.materials = JSON.parse(this.item.qfxx.chatContent || '[]');
          }
          this.form.title = this.item.title;
          this.ecmMarketingTypeRelationId = this.item.ecmMarketingTypeRelationId;
        } else {
          this.isEdit = false;
        }
      },
      immediate: true,
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.chat-item {
  width: 240px;
  height: 100px;
  border: 1px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  cursor: pointer;
  .el-icon-plus {
    color: #1890ff;
    font-size: 24px;
  }
  .add-text {
    margin-top: 12px;
    font-size: 14px;
    font-weight: 400;
    color: #303133;
  }
  &:hover {
    border-color: #1890ff;
  }
}
.task-desc {
  /deep/ .el-input__count {
    background-color: transparent;
    bottom: 0;
  }
}
.card-item {
  margin-top: 10px;
  margin-right: 10px;
}
</style>
