<template>
  <div>
    <el-dialog :title="isEdit && !readOnly ? '编辑企微任务' : '企微任务'" :visible.sync="show" width="630px" @closed="close">
      <dm-steps v-if="!isEdit" style="margin-bottom:30px" class="step-inner" :active="step" finish-status="success">
        <dm-step title="编辑基本信息"></dm-step>
        <dm-step title="配置任务完成方式"></dm-step>
      </dm-steps>
      <div :class="{ wrapper: isEdit }">
        <div v-if="isEdit" class="sub-title">基本信息</div>
        <el-form ref="form" :model="form" :rules="rules" v-show="step == 0 || isEdit" label-width="120px">
          <el-form-item label="选择企业" prop="qywxEnterpriseId">
            <el-select v-model="form.qywxEnterpriseId" @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">
            <el-input show-word-limit v-model="form.title" :maxlength="20" :disabled="readOnly"></el-input>
          </el-form-item>
          <el-form-item label="任务描述" prop="remark">
            <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>
            <template slot="label">
              <span>任务发放规则</span>
              <el-tooltip slot="label" open-delay="200" content="优先所选用户的内容优先级" placement="top">
                <i style="cursor:pointer;color:#909399;font-size:14px;" class="iconfont icon-xinxixianshi"></i>
                <div slot="content" style="line-height:22px;width:350px">任务会按照此处的优先级进行下发。<br />如果客户有①，那么会给①下发线索任务；<br />如果没有①，则会给②下发线索任务，逐步按照优先级判断；<br />如果都没有，则不形成线索任务。</div>
              </el-tooltip>
            </template>
            <div class="rule-header">
              <span>优先级</span>
              <span>发放对象</span>
              <span>排序</span>
            </div>
            <draggable v-model="ruleList" animation="200" handle=".drag" :disabled="readOnly">
              <transition-group>
                <div class="rule-item" v-for="(el, i) in ruleList" :key="el.key">
                  <span>{{ i + 1 }}</span>
                  <span>{{ el.value }}</span>
                  <span>
                    <img class="drag" style="width:16px;height:16px" :style="{ cursor: readOnly ? 'not-allowed' : 'move' }" src="../assets/img/sort.svg" />
                  </span>
                </div>
              </transition-group>
            </draggable>
            <div class="tip">可点击表格处 <img style="width:12px;height:12px;" src="../assets/img/sort2.svg" /> 按钮进行拖拽排序。</div>
          </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>
        <div v-if="isEdit" class="sub-title" style="margin-top:48px">任务完成方式</div>
        <div v-show="step == 1 || isEdit">
          <div class="task-tip">
            <i class="el-icon-info"></i>
            勾选多个，则门店人员通过任一方式即可完成任务。
          </div>
          <div class="task-wrapper">
            <el-checkbox style="margin-top:-6px" label="话务" v-model="form.telFlag" :true-label="1" :false-label="0" :disabled="readOnly"></el-checkbox>
          </div>
          <div class="task-wrapper">
            <el-checkbox style="margin-bottom:0" label="会话" v-model="form.chatFlag" :true-label="1" :false-label="0" :disabled="readOnly"></el-checkbox>
            <span style="color: #909399;font-size:12px;line-height:17px;margin-left:15px">最多可添加 5 个</span>
            <div ref="materialContainer" style="margin-bottom:16px;display:flex;flex-wrap:wrap;margin-top:12px" :class="{ 'material-height': !isEdit }">
              <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 < 5 && !readOnly" class="chat-item card-item" @click="materialVisible = true">
                <i class="el-icon-plus"></i>
                <span class="add-text">添加素材</span>
                <!-- <span style="font-size:12px;line-height:17px;color:#909399;margin-top:3px">最多可添加 5 个</span> -->
              </div>
            </div>
          </div>
          <div class="task-wrapper">
            <el-checkbox label="短信" v-model="form.smsFlag" :true-label="1" :false-label="0" :disabled="readOnly"></el-checkbox>
            <el-row class="sms" type="flex">
              <div class="sms-label">短信内容</div>
              <div class="sms-template-wrapper">
                <div class="sms-template-header">
                  <el-button type="text" @click="openDialog('smsTemplate')" :disabled="readOnly">选择模板</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button type="text" @click="openDialog('transferLink')" :disabled="readOnly">插入小程序链接</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button type="text" @click="openDialog('reduceLink')" :disabled="readOnly">压缩网址</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-popover v-model="showPopover" placement="top" trigger="click" width="600" :offset="148">
                    <div style="padding:8px;position:relative">
                      <i class="el-icon-close popover-close" @click="showPopover = false"></i>
                      <div class="messsage-template-title">模板示例</div>
                      <div class="messsage-template-description">模板示列如下，其中{数字}为可插入的变量值，参照表如下：注意考虑变量值的文本长度，以免超出67字/条的文本上限。</div>
                      <div class="messsage-template-content">
                        <ul>
                          <li>{1}=姓名</li>
                          <li>{2}=姓名+先生/女士</li>
                          <li>{3}=生日日期</li>
                          <li>{4}=生日天数</li>
                          <li>{5}=关注日期</li>
                          <li>{6}=关注天数</li>
                          <li>{7}=主门店品牌名称</li>
                          <li>{8}=主门店名称</li>
                          <li>{9}=主门店电话</li>
                          <li>{10}=专属导购姓名</li>
                          <li>{11}=专属导购手机号</li>
                          <li>{12}=开卡日期</li>
                          <li>{13}=开卡天数</li>
                          <li>{14}=开卡门店名称</li>
                        </ul>
                        <ul>
                          <li>{15}=会员卡号</li>
                          <li>{16}=会员等级名称</li>
                          <li>{17}=主门店地址</li>
                          <li>{18}=会员等级剩余有效天数</li>
                          <li>{19}=积分余额</li>
                          <li>{20}=30天内将过期积分额度</li>
                          <li>{21}=储值余额</li>
                          <li>{22}=消费总额</li>
                          <li>{23}=消费次数</li>
                          <li>{24}=最近消费日期</li>
                          <li>{25}=最近消费间隔</li>
                          <li>{26}=最高单笔消费</li>
                          <li>{27}=最近消费门店名称</li>
                          <li>{28}=最近消费品牌名称</li>
                        </ul>
                      </div>
                    </div>
                    <el-button type="text" slot="reference">查看变量</el-button>
                  </el-popover>
                </div>
                <el-input class="sms-template" v-model="form.smsContent" placeholder="亲爱的{2}，{3}是你的生日，祝你生日快乐，心想事成！" type="textarea" :rows="4" resize="none" show-word-limit :maxlength="450" :readonly="readOnly"></el-input>
              </div>
            </el-row>
          </div>
        </div>
      </div>
      <template slot="footer" v-if="isEdit && !readOnly">
        <el-button style="width:74px" :key="2" @click="close">取消</el-button>
        <el-button style="width:74px" :key="2" type="primary" @click="addItem">确定</el-button>
      </template>
      <template slot="footer" v-else-if="step == 0 && !readOnly">
        <el-button style="width:74px" :key="1" @click="close">取消</el-button>
        <el-button style="width:74px" :key="1" type="primary" @click="onNext">下一步</el-button>
      </template>
      <template slot="footer" v-else-if="step == 1 && !readOnly">
        <el-button style="width:74px" :key="2" @click="step = 0">上一步</el-button>
        <el-button style="width:74px" :key="2" type="primary" @click="addItem">确定</el-button>
      </template>
    </el-dialog>
    <template-dialog ref="template-dialog" @sendItem="onInsertTemplate"></template-dialog>
    <dm-material :visible.sync="materialVisible" @select="onSelectMaterial" :wx-enterprise-id="this.form.qywxEnterpriseId" projectName="marketing" :material-ids="materials.map(el => el.relation_id)"></dm-material>
  </div>
</template>

<script>
import Draggable from 'vuedraggable';
import { getEntepriseList } from '../assets/api';
import TemplateDialog from './qywx-dialog';
import MaterialItem from './material-item';

const ruleMap = {
  1: '专属导购',
  2: '最近消费导购',
  3: '服务门店店长'
};

export default {
  name: 'lib-qywx',
  props: {
    item: {
      type: Object,
      default() {
        return {};
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Draggable,
    TemplateDialog,
    MaterialItem
  },
  data() {
    return {
      step: 0,
      form: {
        qywxEnterpriseId: '',
        qywxEnterpriseName: '',
        remark: '',
        clerkRule: '1,2,3',
        title: '',
        expireDays: 0,
        telFlag: 0,
        chatFlag: 0,
        smsFlag: 0,
        chatContent: null,
        smsContent: null
      },
      rules: {
        qywxEnterpriseId: { required: true, message: '请选择企业', trigger: 'change' },
        title: { required: true, message: '请填写任务标题', trigger: 'blur' },
        remark: { required: true, message: '请填写任务描述', trigger: 'blur' },
        expireDays: { required: true, message: '请填写', trigger: 'blur' }
      },
      ruleList: [
        { key: 1, value: '专属导购' },
        { key: 2, value: '最近消费导购' },
        { key: 3, value: '服务门店店长' }
      ],
      entepriseList: [],
      isEdit: false,
      ecmMarketingTypeRelationId: '',
      showPopover: false,
      materials: [],
      materialVisible: false
    };
  },
  created() {
    this.getEntepriseList();
  },
  methods: {
    close() {
      this.form = {
        qywxEnterpriseId: '',
        qywxEnterpriseName: '',
        remark: '',
        clerkRule: '1,2,3',
        title: '',
        expireDays: 0,
        telFlag: 0,
        chatFlag: 0,
        smsFlag: 0,
        chatContent: null,
        smsContent: null
      };
      this.ecmMarketingTypeRelationId = '';
      this.materials = [];
      this.ruleList = [
        { key: 1, value: '专属导购' },
        { key: 2, value: '最近消费导购' },
        { key: 3, value: '服务门店店长' }
      ];
      this.step = 0;
      this.$refs.form.resetFields();
      this.$emit('update:show', false);
    },
    addItem() {
      let qywx = { ...this.form };
      if (qywx.chatFlag == 0 && qywx.smsFlag == 0 && qywx.telFlag == 0) {
        this.$message.warning('请至少配置一种任务完成方式');
        return;
      }
      if (this.materials.length > 0) {
        qywx.chatContent = JSON.stringify(this.materials.map(el => ({ relation_id: el.relation_id })));
      }
      if (qywx.chatFlag != 0 && !qywx.chatContent) {
        this.$message.warning('请添加会话素材');
        return;
      }
      if (qywx.smsFlag != 0 && !qywx.smsContent) {
        this.$message.warning('请添加短信模板');
        return;
      }
      delete qywx.title;
      if (qywx.smsFlag == 0) {
        qywx.smsContent = null;
      }
      if (qywx.chatFlag == 0) {
        qywx.chatContent = null;
      }
      qywx.clerkRule = this.ruleList.map(el => el.key).join();
      this.$emit('sendItem', { title: this.form.title, qywx, comName: 'qywx', ecmMarketingTypeRelationId: this.ecmMarketingTypeRelationId });
      this.close();
    },
    async onNext() {
      let valid = await this.$refs.form.validate();
      if (valid) {
        this.step = 1;
      }
    },
    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 = [];
      console.log(item, v);
      if (item) {
        this.form.qywxEnterpriseName = item.corpName;
      } else {
        this.form.qywxEnterpriseName = '';
      }
    },
    openDialog(type) {
      // type: reduceLink 压缩链接，transferLink 小程序链接，smsTemplate 短信模板
      this.$refs['template-dialog'][type].show = true;
    },
    onInsertTemplate(item) {
      if (item.type == 1) {
        this.form.smsContent = item.value.originalContent;
      } else if (item.type == 2) {
        if (this.form.smsContent) {
          this.form.smsContent = `${this.form.smsContent} ${item.value}`;
        } else {
          this.form.smsContent = item.value;
        }
      }
      this.form.smsFlag = 1;
    },
    onDeleteMaterial(id) {
      this.materials = this.materials.filter(el => el.relation_id != id);
    },
    onSelectMaterial(item) {
      this.form.chatFlag = 1;
      this.materials.push({
        type: item.materialType,
        relation_id: item.materialId,
        title: item.materialTitle,
        content: item.materialContent || item.link,
        img: item.imgUrl
      });
      this.$nextTick(() => {
        this.$refs.materialContainer.scrollTop = this.$refs.materialContainer.scrollHeight - this.$refs.materialContainer.clientHeight;
      });
    }
  },
  watch: {
    show: {
      handler() {
        if (Object.keys(this.item).length > 0) {
          this.isEdit = true;
          for (let key in this.form) {
            if (this.item.qywx[key] !== undefined) {
              this.form[key] = this.item.qywx[key];
            }
          }
          if (this.item.qywx && this.item.qywx.chatContent) {
            this.materials = JSON.parse(this.item.qywx.chatContent || '[]');
          }
          this.ruleList = this.item.qywx.clerkRule.split(',').map(el => ({
            key: parseInt(el),
            value: ruleMap[el]
          }));
          this.form.title = this.item.title;
          this.ecmMarketingTypeRelationId = this.item.ecmMarketingTypeRelationId;
        } else {
          this.isEdit = false;
        }
      },
      immediate: true,
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.task-wrapper {
  border: 1px solid#DCDFE6;
  padding: 20px;
  padding-bottom: 0;
  .el-checkbox {
    margin-bottom: 12px;
    color: #303133;
  }
}
.task-wrapper + .task-wrapper {
  margin-top: 10px;
}
.rule-header,
.rule-item {
  display: flex;
  line-height: 32px;
  color: #303133;
  span {
    flex: 1;
    padding: 0 20px;
  }
  span:last-child {
    text-align: right;
  }
}
.rule-header {
  background-color: #f1f3f7;
}
.tip {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  display: flex;
  align-items: center;
  img {
    margin: 0 3px;
  }
}
.sub-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  line-height: 20px;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  &::before {
    content: '';
    width: 3px;
    display: inline-block;
    height: 14px;
    background: #1890ff;
    margin-right: 8px;
  }
}
.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;
    }
  }
}
.chat-item {
  width: 240px;
  height: 100px;
  border: 1px dotted #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;
  }
}
.messsage-template {
  &-description {
    font-size: 12px;
    font-weight: 400;
    color: #606266;
    line-height: 17px;
    margin: 23px 0 20px;
  }
  &-title {
    font-size: 18px;
    font-weight: 400;
    color: #303133;
    line-height: 18px;
  }
  &-content {
    display: flex;
    line-height: 28px;
    background: #fafafa;
    border-radius: 2px;
    padding: 16px 0 16px 40px;
    ul {
      flex: 1;
    }
  }
}
.popover-close {
  position: absolute;
  right: 5px;
  top: 5px;
  &:hover {
    color: #1890ff;
  }
}
.task-desc {
  /deep/ .el-input__count {
    background-color: transparent;
    bottom: 0;
  }
}
.card-item {
  margin-top: 10px;
  margin-right: 10px;
}
/deep/ .dm-step .dm-step-box.is-process .dm-step__icon {
  background-color: #1890ff;
  border-color: #1890ff;
}
/deep/.dm-step .dm-step-box.is-finish,
/deep/.dm-step .dm-step-box.is-success {
  color: #1890ff;
  border-color: #1890ff;
}
.task-tip {
  width: 374px;
  height: 36px;
  background: #e6f7ff;
  border-radius: 4px;
  border: 1px solid #91d5ff;
  font-weight: 400;
  color: #606266;
  line-height: 36px;
  margin-bottom: 10px;
  i {
    color: #1890ff;
    font-size: 12px;
    margin: 0 5px 0 15px;
  }
}
.wrapper {
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
}
.material-height {
  max-height: 120px;
  overflow-x: hidden;
  overflow-y: auto;
  scroll-behavior: smooth;
}
</style>
