<template>
  <div>
    <el-dialog custom-class="dialogClass" :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 class="is-required" 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-item class="is-required" label="群发失败设置">
          <el-radio-group :disabled="readOnly" v-model="form.failSetting" @change="onChangeFailSetting">
            <el-radio :label="1" style="margin-right:0">开启</el-radio>
            <el-radio :label="0" style="margin-left:20px">不开启</el-radio>
          </el-radio-group>
          <div class="tips">开启则可针对群发任务下发失败的人群进行其他方式的营销</div>
          <div class="tips">( 所选人群中非企业企微好友的，群发任务会下发失败 )</div>
          <div ref="task" v-if="form.failSetting == 1">
            <div class="task-wrapper" style="margin-top:16px;padding-top:14px;">
              <el-row style="margin-bottom:12px" type="flex" align="middle" justify="space-between">
                <el-checkbox label="话务" style="margin-bottom:0" :value="form.telFlag" :true-label="1" :false-label="0" :disabled="readOnly" @change="onChangeTelTask"></el-checkbox>
                <el-button v-if="form.teltask && !readOnly" type="text" @click="onEditTelTask">编辑</el-button>
              </el-row>
              <div style="margin-bottom:14px" v-if="form.teltask">
                <div class="clearfix">
                  <div class="fl teltask-title" style="font-size:16px;color:#303133">{{ form.teltask.title }}</div>
                  <div class="fr" style="color:#606266">任务逾期判定{{ form.teltask.lateDays }}天之后</div>
                </div>
                <div style="margin-top:12px;color:#606266">{{ form.teltask.content }}</div>
              </div>
            </div>
            <div class="task-wrapper" style="margin-top:16px;padding-top:14px;">
              <el-row style="margin-bottom:12px" type="flex" align="middle" justify="space-between">
                <el-checkbox label="短信" style="margin-bottom:0" :value="form.smsFlag" :true-label="1" :false-label="0" :disabled="readOnly" @change="onChangeSms"></el-checkbox>
                <el-button v-if="form.gicSmsTemplateId && !readOnly" type="text" @click="messageDialogShow = true">重新选择</el-button>
              </el-row>
              <div style="margin-bottom:14px" v-if="form.gicSmsTemplateId">
                <div class="teltask-title" style="font-size:16px;color:#303133">{{ sms.title }}<template v-if="form.gicSmsTemplateId == -1">( 短信模板已删除 )</template></div>
                <div v-if="form.gicSmsTemplateId != -1" style="margin-top:12px;color:#606266">{{ sms.content }}</div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template v-if="!readOnly" 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>
    <lib-teltask :item="telTaskItem" :show.sync="teltaskDialogShow" @sendItem="addTeltask"></lib-teltask>
    <lib-message v-if="messageDialogShow" :show.sync="messageDialogShow" @sendItem="onInsertTemplate"></lib-message>
    <dm-material :visible.sync="materialVisible" :types="[1, 2, 3, 4, 6]" @select="onSelectMaterial" :wx-enterprise-id="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.vue';
import LibMessage from './lib-Message.vue';
import LibTeltask from './lib-teltask.vue';

export default {
  name: 'lib-qfxx',
  props: {
    item: {
      type: Object,
      default() {
        return {};
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  components: {
    MaterialItem,
    LibMessage,
    LibTeltask
  },
  data() {
    return {
      form: {
        qfxxEnterpriseId: '',
        qfxxEnterpriseName: '',
        remark: '',
        title: '',
        expireDays: 0,
        failSetting: '',
        gicSmsTemplateId: '',
        telFlag: 0,
        smsFlag: 0,
        teltask: 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,
      showPopover: false,
      telTaskItem: {},
      teltaskDialogShow: false,
      sms: {},
      messageDialogShow: false
    };
  },
  created() {
    this.getEntepriseList();
  },
  methods: {
    onChangeFailSetting(flag) {
      if (flag) {
        this.$nextTick(() => {
          if (this.$refs.task) {
            this.$refs.task.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
          }
        });
      }
    },
    onInsertTemplate(item) {
      console.log(item);
      this.sms = {
        title: item.title,
        content: item.originalContent
      };
      this.form.gicSmsTemplateId = item.gicSmsTemplateId;
      this.form.smsFlag = 1;
      this.messageDialogShow = false;
      this.onChangeFailSetting(true);
    },
    openMaterialDialog() {
      if (!this.form.qfxxEnterpriseId) {
        return this.$message.warning('请选择企业');
      }
      this.materialVisible = true;
    },
    close() {
      this.form = {
        qfxxEnterpriseId: '',
        qfxxEnterpriseName: '',
        remark: '',
        title: '',
        expireDays: 0,
        failSetting: '',
        gicSmsTemplateId: '',
        telFlag: 0,
        smsFlag: 0,
        teltask: null
      };
      this.ecmMarketingTypeRelationId = '';
      this.materials = [];
      this.sms = {};
      this.telTaskItem = {};
      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;
      }
      if (this.form.failSetting === '') {
        return this.$message.warning('请选择是否开启群发消息失败设置');
      }
      if (this.form.failSetting == 1 && this.form.smsFlag == 0 && this.form.telFlag == 0) {
        return this.$message.warning('请至少设置一种群发失败方式');
      }
      if (qfxx.failSetting == 0) {
        qfxx.telFlag = 0;
        qfxx.smsFlag = 0;
      }
      if (qfxx.telFlag == 0) {
        delete qfxx.teltask;
      }
      if (qfxx.smsFlag == 0) {
        delete qfxx.gicSmsTemplateId;
      }
      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
      });
    },
    onChangeTelTask(val) {
      if (val && !this.form.teltask) {
        this.teltaskDialogShow = true;
      } else {
        this.form.telFlag = val;
      }
    },
    onChangeSms(val) {
      if (val && !this.form.gicSmsTemplateId) {
        this.messageDialogShow = true;
      } else {
        this.form.smsFlag = val;
      }
    },
    onEditTelTask() {
      this.telTaskItem = {
        ecmMarketingTypeRelationId: 1, // 有值时为编辑， 兼容已有话务组件
        ...this.form.teltask
      };
      this.teltaskDialogShow = true;
    },
    addTeltask(item) {
      this.form.teltask = {
        title: item.title,
        content: item.content,
        lateDays: item.lateDays
      };
      this.form.telFlag = 1;
      this.onChangeFailSetting(true);
    }
  },
  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.sms = {
            content: this.item.qfxx.smsContent,
            title: this.item.qfxx.smsTitle
          };
          console.log(this.sms);
          this.ecmMarketingTypeRelationId = this.item.ecmMarketingTypeRelationId;
        } else {
          this.isEdit = false;
        }
      },
      immediate: true,
      deep: true
    }
  }
};
</script>

<style lang="scss">
.dialogClass {
  .el-dialog__body {
    max-height: 600px;
    overflow-y: auto;
  }
}
</style>

<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;
}
.task-wrapper {
  line-height: initial;
  border: 1px solid#DCDFE6;
  padding: 20px;
  padding-bottom: 0;
  .el-checkbox {
    margin-bottom: 12px;
    color: #303133;
  }
}
.task-wrapper + .task-wrapper {
  margin-top: 10px;
}
.sms {
  margin-bottom: 16px;
  &-label {
    margin-left: 23px;
    margin-top: 8px;
    color: #303133;
  }
  &-template-wrapper {
    margin-left: 12px;
    border: 1px solid #dcdfe6;
    flex: 1;
    border-radius: 4px;
  }
  &-template-header {
    padding: 10px 0;
    margin: 0 10px;
    border-bottom: 1px solid #dcdfe6;
  }
  &-template {
    margin-top: 5px;
    /deep/ .el-textarea__inner {
      border: 0;
      word-break: break-word;
    }
  }
}
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
}
.teltask-title {
  max-width: 300px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
</style>
