<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-09-18 15:25:12
 * @LastEditors: 无尘
 * @LastEditTime: 2019-12-06 17:17:08
 -->

<!--
<chat-log :brandId="brandId"></chat-log>
import chatLog from '@/components/app/chat-log.vue';
components: {
  chatLog
}
-->

<template>
  <div class="app-detail-wrap">
    <div class="chat-log boder-box">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <div class="new-card-body">
        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="选择卡券:" prop="coupCardId">
            <div class="search-div">
              <el-input placeholder="请输入卡券名称" v-model="searchInput" class="w-264" style="width: 264px;" clearable @keyup.native="value => toInput(value, searchInput)" @clear="clearInput"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input><span class="search-tip p-l-20 font-14 color-909399">领取限制&lt;100的卡券不支持选择，系统已过滤，符合条件共{{ total }}张</span>
            </div>
            <div class="chat-log-content boder-box m-t-20">
              <el-table :data="tableData" style="width: 100%">
                <el-table-column label="" width="50">
                  <template slot-scope="scope">
                    <el-radio v-model="selectCoupCardId" :disabled="scope.row.selected == 1 ? true : false" :label="scope.row.coupCardId">{{ '' }}</el-radio>
                  </template>
                </el-table-column>
                <el-table-column prop="cardName" label="卡券名称" show-overflow-tooltip></el-table-column>
                <el-table-column label="备注名" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.subName }}
                  </template>
                </el-table-column>
                <el-table-column prop="effectDateString" label="有效期" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="cardLimit" label="领取限制" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="storeMode" label="适用门店" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.storeMode == 0 ? '所有门店' : scope.row.storeMode == 1 ? '部分分组' : '部分门店' }}
                  </template>
                </el-table-column>
                <el-table-column prop="couponStock" label="库存" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="getedQuantity" label="领取次数" show-overflow-tooltip> </el-table-column>
              </el-table>
              <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
                <el-pagination background @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout=" prev, pager, next" :total="total"> </el-pagination>
              </div>
            </div>
          </el-form-item>
          <div class="el-form-item el-form-item--large">
            <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
              <el-tooltip class="item" effect="dark" content="卡券的发送范围设置" placement="top-start">
                <span>选择发送范围<span class="el-icon-info font-12 color-909399"></span> :</span></el-tooltip
              >
            </label>
            <div class="el-form-item__content" style="margin-left: 120px;">
              <el-radio v-model="formData.sendRange" label="0" @change="changeRange">所有门店</el-radio>
              <el-radio class="m-l-40" v-model="formData.sendRange" label="1" @change="changeRange">部分分组</el-radio>
              <div v-if="formData.sendRange == 1" class="w-240 inline-block item-cell-select">
                <div class="depart-item-wrap">
                  <div style="width:213px" class="el-select el-select--large depart-item-content" @click="showDialogLayer('group', formData.selectList)">
                    <div class="el-select__tags" style="max-width: 181px;">
                      <span>
                        <template v-for="(item, index) in formData.selectList">
                          <span class="el-tag el-tag--info el-tag--small" :key="index">
                            <span class="el-select__tags-text">{{ item.name || item.storeName }}</span
                            ><i class="el-tag__close el-icon-close" @click.stop="delDepart(index, formData.selectList)"></i>
                          </span>
                        </template>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              <el-radio class="m-l-40" v-model="formData.sendRange" label="2" @change="changeRange">部分门店</el-radio>
              <div v-if="formData.sendRange == 2" class="w-240 inline-block  item-cell-select">
                <div class="depart-item-wrap">
                  <div style="width:213px" class="el-select el-select--large depart-item-content" @click="showDialogLayer('store', formData.selectList)">
                    <div class="el-select__tags" style="max-width: 181px;">
                      <span>
                        <template v-for="(item, index) in formData.selectList">
                          <span class="el-tag el-tag--info el-tag--small" :key="index">
                            <span class="el-select__tags-text">{{ item.name || item.storeName }}</span
                            ><i class="el-tag__close el-icon-close" @click.stop="delDepart(index, formData.selectList)"></i>
                          </span>
                        </template>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="(formData.sendRange == '1' || formData.sendRange == '2') && !formData.selectList.length" class="el-form-item__error">请选择发送范围</div>
            </div>
          </div>
          <div class="el-form-item el-form-item--large">
            <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
              <el-tooltip class="item" effect="dark" content="卡券限制每个会员最大发放次数" placement="top-start">
                <span>券发放张数<span class="el-icon-info font-12 color-909399"></span> :</span></el-tooltip
              >
            </label>
            <div class="el-form-item__content" style="margin-left: 120px;"><el-input-number class="w-90" v-model="formData.eachSendTimes" controls-position="right" :min="0" :max="20"></el-input-number><span class="font-14 color-c0c4cc p-l-20">最多20张每人</span></div>
          </div>
          <div class="el-form-item el-form-item--large">
            <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
              <el-tooltip class="item" effect="dark" content="卡券发放总数，不得超过券库存数" placement="top-start">
                <span>券发放总数<span class="el-icon-info font-12 color-909399"></span> :</span></el-tooltip
              >
            </label>
            <div class="el-form-item__content" style="margin-left: 120px;">
              <el-radio v-model="formData.sendType" label="0">无限制</el-radio>
              <el-radio class="m-l-40" v-model="formData.sendType" label="1">限制总数</el-radio><el-input-number v-if="formData.sendType == 1" class="m-l-10" v-model="formData.totalSendTimes" controls-position="right" :min="1"></el-input-number>
            </div>
          </div>
          <!-- <div class="el-form-item el-form-item--large">
            <label for="name" class="el-form-item__label" style="width: 120px; cursor: pointer;">
              <el-tooltip class="item" effect="dark" content="卡券领取总数，不得超过券库存数" placement="top-start">
                <span>券领取总数<span class="el-icon-info font-12 color-909399"></span> :</span></el-tooltip
              >
            </label>
            <div class="el-form-item__content" style="margin-left: 120px;">
              <el-radio v-model="formData.receiveType" label="0">无限制</el-radio>
              <el-radio class="m-l-40" v-model="formData.receiveType" label="1">限制总数</el-radio><el-input-number v-if="formData.receiveType == 1" class="m-l-10" v-model="formData.totalReceiveTimes" controls-position="right" :min="1"></el-input-number>
            </div>
          </div> -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">确认{{ $route.query.coupCardId ? '编辑' : '新建' }}</el-button>
            <el-button v-if="!$route.query.coupCardId" type="primary" @click="submitForm('ruleForm', 'flag')">保存并继续</el-button>
            <el-button @click="toReturn">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <vue-select-store ref="storeSelector" :currentBrand="activeGroup" :appScene="appScene" :treeSet="storeTreeSet" selectType="store" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
    <vue-select-store ref="storeSelectorGroup" :currentBrand="activeGroup" :appScene="appScene" :treeSet="groupTreeSet" selectType="group" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import vueSelectStore from 'components/common/vueSelectStore';
import { getRequest, postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'chat-log',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    commonDetailTop,
    vueSelectStore
  },
  data() {
    const validateRange = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择发送范围'));
      } else if ((value == '1' || value == '2') && !this.formData.selectList.length) {
        return callback(new Error('请选择发送范围'));
      } else {
        callback();
      }
    };
    const validateSendType = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择券发放总数'));
      } else if (value == '1' && !this.formData.totalSendTimes) {
        return callback(new Error('请选择券发放总数'));
      } else {
        callback();
      }
    };
    /* const validateReceiveType = (rule, value, callback) => {
      if (value == '') {
        return callback(new Error('请选择券领取总数'));
      } else if (value == '1' && !this.formData.totallReceiveTimes) {
        return callback(new Error('请选择券领取总数'));
      } else {
        callback();
      }
    }; */
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '3',
      topMenuData: [
        {
          id: '1',
          name: '在线沟通设置',
          path: `/onlineChatSet?appIcon=${this.$route.query.appIcon}&activeTab=${this.$route.query.activeTab}`
        },
        {
          id: '2',
          name: '卡券列表',
          path: `/onlineChatSet?appIcon=${this.$route.query.appIcon}&activeTab=${this.$route.query.activeTab}`
        },
        {
          id: '3',
          name: this.$route.query.coupCardId ? '编辑卡券' : '新增卡券'
        }
      ],
      selectCoupCardId: '',
      selectList: '',
      tableData: [],
      // 条件
      conditionObj: {
        searchInput: ''
      },

      // 门店选择
      appScene: 2,
      defaultStoreList: [],
      selectType: 'store',
      storeTreeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      },
      groupTreeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      },

      // 分页参数
      currentPage: 1,
      pageSize: 6,
      total: 0,
      formData: {
        id: '',
        coupCardId: '',
        sendRange: '0',
        selectList: [],
        eachSendTimes: 3,
        sendType: '0',
        totalSendTimes: 0
        // receiveType: '0',
        // totalReceiveTimes: 0
      },
      rules: {
        coupCardId: [{ required: true, message: '请选择卡券', trigger: 'change' }],
        sendRange: [{ validator: validateRange, trigger: 'change' }],
        sendType: [{ validator: validateSendType, trigger: 'change' }],
        // receiveType: [{ validator: validateReceiveType, trigger: 'change' }],
        eachSendTimes: [{ required: true, message: '请输入券发放张数', trigger: 'blur' }]
      }
    };
  },
  methods: {
    /**
     * 确认新建
     */
    submitForm(formName, flag) {
      const that = this;
      that.formData.coupCardId = that.selectCoupCardId;
      if ((that.formData.sendRange == '1' || that.formData.sendRange == '2') && !that.formData.selectList.length) {
        return false;
      }
      if (that.formData.sendType == '1' && !that.formData.totalSendTimes) {
        return false;
      }
      if (that.formData.receiveType == '1' && !that.formData.totalReceiveTimes) {
        return false;
      }
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        }
      });
    },
    postSaveCard(flag) {
      const that = this;
      let para = {
        id: that.formData.id,
        coupCardId: that.formData.coupCardId,
        sendRange: that.formData.sendRange,
        selectList: that.formData.sendRange == 1 ? that.formData.selectList.map(item => item.groupId || item.id).join(',') : that.formData.sendRange == 2 ? that.formData.selectList.map(item => item.storeId || item.id).join(',') : '',
        eachSendTimes: that.formData.eachSendTimes,
        sendType: that.formData.sendType,
        totalSendTimes: that.formData.totalSendTimes,
        // receiveType: that.formData.receiveType,
        // totalReceiveTimes: that.formData.totalReceiveTimes,
        brandId: that.brandId
      };
      postRequest(that.$route.query.coupCardId ? '/haoban-app-member-web/cardCoupon/edit-card-coup' : '/haoban-app-member-web/cardCoupon/add-card-coup', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg(that.$route.query.coupCardId ? '编辑卡券成功' : '新建卡券成功', 'success');
            if (!flag) {
              that.$router.push(`/onlineChatSet?activeTab=${that.$route.query.activeTab}&appIcon=${that.$route.query.appIcon}`);
            } else {
              that.formData = {
                id: '',
                coupCardId: '',
                sendRange: '0',
                selectList: [],
                eachSendTimes: 3,
                sendType: '0',
                totalSendTimes: 0
                // receiveType: '0',
                // totalReceiveTimes: 0
              };
              // 禁用
              that.tableData.forEach(ele => {
                if (ele.coupCardId == that.selectCoupCardId) {
                  ele.selected = 1;
                }
              });
              that.$nextTick(() => {
                that.selectCoupCardId = '';
              });
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    toReturn() {
      this.$router.go(-1);
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 200),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * 改变选择范围
     */
    changeRange(e) {
      const that = this;
      that.formData.selectList = [];
    },

    // 门店弹窗显示
    showDialogLayer(type, selData) {
      const that = this;
      that.selectType = type;
      that.defaultStoreList = selData;
      if (type == 'store') {
        that.storeTreeSet = {
          dialogVisible: true,
          isSingle: false,
          isSelectPerson: true,
          openNextBool: true // 展开下级不调用接口
        };
      } else {
        that.groupTreeSet = {
          isSelectPerson: false, // 控制只能选部门(false)
          dialogVisible: true, // 控制显示/隐藏
          isSingle: false, // 是否单选
          openNextBool: true // 展开下级不调用接口
        };
      }
    },
    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      // type:	1:员工,2:部门,3:门店;
      const that = this;
      that.formData.selectList = group;
      that.defaultStoreList = group;
    },
    /**
     * 删除选的部门
     */
    delDepart(index, obj, type) {
      obj.splice(index, 1);
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },

    /**
     * 获取卡券数据
     */
    getCardData() {
      const that = this;
      let para = {
        coupCardId: that.$route.query.coupCardId,
        brandId: that.brandId
      };
      getRequest('/haoban-app-member-web/cardCoupon/find-card-coup-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result.list) {
              resData.result.list.forEach(ele => {
                ele.label = ele.name;
              });
            }
            that.formData = {
              id: resData.result.detail.id,
              coupCardId: resData.result.detail.coupCardId,
              sendRange: String(resData.result.detail.sendRange),
              selectList: resData.result.detail.sendRange != 0 ? resData.result.list : [],
              eachSendTimes: resData.result.detail.eachSendTimes,
              sendType: String(resData.result.detail.sendType),
              totalSendTimes: resData.result.detail.totalSendTimes
              // receiveType: String(resData.result.detail.receiveType),
              // totalReceiveTimes: resData.result.detail.totalReceiveTimes
            };
            that.defaultStoreList = resData.result.detail.sendRange != 0 ? resData.result.list : [];
            that.selectCoupCardId = resData.result.detail.coupCardId;
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      let para = {
        cardName: that.searchInput || '', // 搜索字段
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        brandId: that.activeBrand
        // taskType: 1 //0不良评价，1话务任务
      };
      getRequest('/haoban-app-member-web/cardCoupon/find-select-card-page', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.pageInfo.total;
            if (that.$route.query.coupCardId) {
              that.getCardData();
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeBrand = newData;
        that.getTableList();
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '2');
    if (that.brandId) {
      that.getTableList();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-240 {
  width: 240px;
}
.w-90 {
  width: 90px;
}
.m-l-40 {
  margin-left: 40px;
}
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  .el-select__tags {
    overflow: hidden;
    white-space: nowrap;
  }
}

.el-form-item.is-error {
  /deep/ .el-input__inner {
    border-color: #dcdfe6;
    &:focus {
      border-color: #dcdfe6;
    }
  }
}
.chat-log {
  width: 100%;
  .w-103 {
    width: 103px;
  }
  .w-369 {
    width: 369px;
  }
  .el-input {
    /deep/ .el-input-group__prepend {
      background-color: #fff;
    }
  }
  .new-card-body {
    padding: 20px;
    .search-tip {
      display: inline-block;
      line-height: 32px;
    }
  }
  .chat-log-content {
    .el-button--primary.is-plain {
      color: #1890ff;
      background: #fff;
      border-color: #1890ff;
      &:hover {
        color: #fff;
        background: #1890ff;
        border-color: #1890ff;
      }
      &.is-disabled.is-plain {
        background-color: #f5f7fa;
        border-color: #dcdfe6;
        color: #c0c4cc;
      }
    }
  }
}
</style>
