<template>
  <div class="ruleFilter">
    <div class="echo-member-group" v-if="echoFlag">
      <div class="subTitle">
        <div class="line"></div>
        <div class="text">
          <div class="space-between">
            已选分组
            <span v-if="!onlyRead"><el-button type="text" class="delBtn" @click="delAll">删除</el-button><el-button type="text" @click="edit">编辑</el-button></span>
          </div>
        </div>
      </div>
      <div class="echoLine" v-for="item in echoData" :key="item.esScreeningWidgetChainId">
        <span class="groupName"> {{ item.chainNodeName }}</span>
        <div class="groupContent">{{ item.selectValue }}</div>
      </div>
    </div>
    <el-dialog title="设置规则" :visible.sync="visiable" width="900px" :before-close="close">
      <div class="container">
        <div class="left">
          <el-tabs tab-position="left" @tab-click="onTabsClick" v-model="activeName">
            <el-tab-pane :label="item.chainNodeName" :name="item.esScreeningWidgetChainId" v-for="item in conditionTypeList" :key="item.esScreeningWidgetChainId" v-loading="tabPaneLoading">
              <div v-if="!item.disable">
                <div v-if="item.templateCode == 'tag001' && templateCode == 'tag001'" class="leftContent">
                  <el-checkbox-group v-model="item.selectValue" @change="val => handleChange(val, item.esScreeningWidgetChainId)" class="checkBoxContainer">
                    <el-checkbox v-for="row in item.selectList" :key="row.key" :label="row.key">{{ row.value }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="item.templateCode == 'com026' && templateCode == 'com026'" class="leftContent">
                  <div class="line" v-for="(value, index) in item.selectList" :key="index">
                    <h3>{{ value.title }}</h3>
                    <el-checkbox-group v-model="item.selectValue" @change="val => handleChange(val, item.esScreeningWidgetChainId)" class="checkBoxContainer">
                      <el-checkbox v-for="row in value.data" :key="row.key" :label="row.key">{{ row.value }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
                <div v-if="item.templateCode == 'com020' && templateCode == 'com020'" class="leftContent">
                  <dm-store-selector v-if="item.templateCode == 'com020'" ref="storeSelector" scenes="auth" scenesVal="marketing" @store-change="val => storeChange(val, item.esScreeningWidgetChainId)" :uuid.sync="item.value"></dm-store-selector>
                </div>
              </div>
              <div v-else>
                不支持选择
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="right">
          <div class="right-top">
            已选条件
          </div>
          <ul class="right-content" v-loading="selectDataLoading">
            <li class="contact-li" v-for="(item, index) in selectData" :key="index">
              <div class="li-cell cursor-pointer">{{ item.chainNodeName }} <i v-if="!readonly" class="el-icon-close" @click="deleteRow(item)"></i></div>
              <span> {{ item.selectValue }}</span>
            </li>
          </ul>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm" :loading="loading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs';
import transform from './createParams.js';

export default {
  name: 'ruleFilter',
  data() {
    return {
      activeName: '',
      conditionTypeList: [], // 第一层级
      templateCode: '', //当前控件类型
      echoFlag: false,
      echoData: [],
      loading: false,
      tabPaneLoading: false,
      selectDataLoading: false
    };
  },
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    sceneCode: {
      type: String,
      default: 'member02'
    },
    requestProject: {
      type: String,
      default: 'gic-web'
    },
    memberCrowdWidgetId: {
      type: [String, Number],
      default: ''
    },
    hideId: {
      type: Array,
      default: () => []
    },
    onlyRead: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    this.getDataList();
  },
  watch: {
    memberCrowdWidgetId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.echoFlag = true;
          this.getEchoData();
        }
      }
    },
    hideId(val) {
      console.log(val);
      if (val && val.length) {
        this.conditionTypeList.filter(item => val.includes(item.esScreeningWidgetChainId)).forEach(item => (item.disable = true));
      } else {
        this.conditionTypeList.forEach(item => (item.disable = false));
      }
    },
    visiable(val) {
      if (val && this.memberCrowdWidgetId) {
        this.getEchoData();
      }
    }
  },
  computed: {
    selectData() {
      const data = this.handleEchoData(this.conditionTypeList);
      console.log(data);
      return data;
    }
  },
  methods: {
    getEchoData() {
      const data = { memberCrowdWidgetId: this.memberCrowdWidgetId };
      this.axios.post(`api-plug/query-member-crowd-new?requestProject=${this.requestProject}`, data).then(res => {
        let resData = res.data;
        if (resData.errorCode == 0) {
          const filterFrontShow = JSON.parse(resData.result.filterFrontShow);
          filterFrontShow.forEach(item => {
            const obj = this.conditionTypeList.find(val => val.esScreeningWidgetChainId == item.esScreeningWidgetChainId);
            if (obj) {
              obj.selectValue = item.selectValue;
              obj.value = item.value;
              obj.selectList = item.selectList;
            }
          });
          this.echoData = this.handleEchoData(filterFrontShow);
        }
      });
    },
    handleEchoData(data) {
      let arr = [];
      data.forEach(item => {
        if (item.selectValue && item.selectValue.length) {
          let selectValue = [];
          if (item.templateCode == 'com026') {
            let myMap = new Map();
            item.selectList.forEach(item => {
              item.data.forEach(val => {
                myMap.set(val.key, val.value);
              });
            });
            item.selectValue.forEach(key => {
              selectValue.push(myMap.get(key));
            });
            selectValue = selectValue.join('，');
          } else if (item.templateCode == 'tag001') {
            item.selectList.forEach(obj => {
              if (item.selectValue.includes(obj.key)) {
                selectValue.push(obj.value);
              }
            });
            selectValue = selectValue.join('，');
          } else if (item.templateCode == 'com020') {
            selectValue = item.selectValue;
          }
          arr.push({ chainNodeName: item.chainNodeName, selectValue, esScreeningWidgetChainId: item.esScreeningWidgetChainId });
        }
      });
      return arr;
    },
    echoStoreSelectorData(key) {
      return new Promise((resolve, reject) => {
        this.$refs.storeSelector[0]
          .getStoreConfig()
          .then(async data => {
            console.log(data);
            if (data.type == 0) {
              resolve(false);
            } else {
              const str = data.list.map(item => item.name).join('，');
              resolve(str);
            }
          })
          .catch(() => {
            resolve(false);
          });
      });
      // 取得门店筛选器的文字回显
    },
    delAll() {
      this.conditionTypeList.forEach(item => {
        item.selectValue = [];
        item.value = '';
      });
      this.activeName = this.conditionTypeList.length && this.conditionTypeList[0].esScreeningWidgetChainId;
      this.$emit('save', '', '');
      this.echoFlag = false;
    },
    edit() {
      this.$emit('update:visiable', true);
    },
    deleteRow(row) {
      this.conditionTypeList.forEach(item => {
        if (item.esScreeningWidgetChainId == row.esScreeningWidgetChainId) {
          item.selectValue = [];
          item.value = '';
        }
      });
    },
    handleChange(val, id) {
      this.conditionTypeList.find(item => item.esScreeningWidgetChainId == id).value = val.join(' ');
    },
    storeChange(uuid, esScreeningWidgetChainId) {
      const obj = this.conditionTypeList.find(item => item.esScreeningWidgetChainId == esScreeningWidgetChainId);
      this.$nextTick(() => {
        this.echoStoreSelectorData(uuid).then(res => {
          if (res) {
            obj.selectValue = res;
            obj.value = uuid;
          }
        });
      });
      console.log(this.conditionTypeList);
    },
    onTabsClick(val) {
      const { name } = val;
      this.getNode(name);
    },
    close() {
      this.$emit('update:visiable', false);
    },
    confirm() {
      const { data, bool } = transform(this.conditionTypeList, this.sceneCode);
      console.log(data);
      console.log(bool);
      if (!bool) {
        this.$message.warning('请选择条件');
        return;
      }
      this.loading = true;
      this.axios
        .post(`api-plug/save-member-crowd-new?requestProject=${this.requestProject}`, data)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            this.$emit('save', resData.result, data);
            this.echoFlag = true;
            this.$emit('update:visiable', false);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取列表
    getDataList() {
      let para = {
        sceneCode: this.sceneCode,
        requestProject: this.requestProject
      };
      this.axios
        .post('/api-plug/get-screening-init-data', qs.stringify(para))
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            resData.result.forEach(item => {
              const { chainNodeName, widget, esScreeningWidgetChainId, columnKey, computeCharacter, dealKey, property } = item;
              this.conditionTypeList.push({
                chainNodeName,
                templateCode: widget.templateCode,
                esScreeningWidgetChainId,
                columnKey,
                computeCharacter,
                dealKey,
                property,
                selectValue: [], // 已选条件的文案
                selectList: [], // 复选框的条件
                value: '' // 提交的值
              });
            });
            this.activeName = this.conditionTypeList.length && this.conditionTypeList[0].esScreeningWidgetChainId;
            this.getNode(this.activeName);
            return;
          }
          this.$message.error({
            duration: 1000,
            message: resData.message
          });
        })
        .catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    getNode(widgetChainId) {
      // 第二层节点的控件类型
      this.axios.get(`/api-plug/get-screening-widget-chain-detail?requestProject=${this.requestProject}&widgetChainId=${widgetChainId}`).then(res => {
        const {
          esScreeningWidgetChainId,
          widget: { sourceFlag, templateCode, widgetParam, widgetValues },
          widgetFieldKey
        } = res.data.result; // 返回的结果 从第一层开始
        this.templateCode = templateCode;
        if (sourceFlag == 1) {
          // 有接口
          const url = JSON.parse(widgetParam)[0].value;
          this.getChildNode(url, widgetFieldKey, esScreeningWidgetChainId);
        } else {
          if (templateCode == 'tag001') {
            this.conditionTypeList.find(item => item.esScreeningWidgetChainId == esScreeningWidgetChainId).selectList = JSON.parse(widgetValues);
          }
        }
      });
    },
    // 使用接口获取 第二层控件类型的内容
    getChildNode(url, key, id) {
      const param = {
        requestProject: this.requestProject,
        key
      };
      this.tabPaneLoading = true;
      this.axios
        .post(`${url}`, qs.stringify(param))
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            this.conditionTypeList.find(item => item.esScreeningWidgetChainId == id).selectList = resData.result;
          }
        })
        .finally(() => {
          this.tabPaneLoading = false;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  background: #ffffff;
  display: flex;
}
.delBtn {
  color: #f5222d;
}
.space-between {
  display: flex;
  justify-content: space-between;
}
.subTitle {
  width: 100%;
  height: 40px;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  .line {
    width: 2px;
    height: 14px;
    background: #2f54eb;
    margin-right: 8px;
  }
  .text {
    font-size: 14px;
    color: #303133;
    width: 100%;
  }
}
.ruleFilter {
  width: 400px;
}
.echo-member-group {
  width: 100%;
  background: #f7f8fa;
  border-radius: 4px;
  padding: 0 15px 15px 15px;
  box-sizing: border-box;
  .echoLine {
    margin-bottom: 16px;
    line-height: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .dot {
      display: inline-block;
      width: 6px;
      height: 6px;
      background: #2f54eb;
      border-radius: 3px;
      margin-right: 6px;
    }
    .groupName {
      font-weight: bolder;
    }
    .groupContent {
      word-break: break-word;
    }
    &:first-child {
      margin-top: 20px;
    }
  }
}
.left {
  width: 566px;
  height: 550px;
  background: #ffffff;
  border-radius: 4px;
  padding: 10px 0;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  .leftContent {
    width: 100%;
    padding: 0 15px 0 5px;
    box-sizing: border-box;
    height: 550px;
    overflow-y: auto;
  }
}
.right {
  width: 274px;
  height: 550px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-left: 12px;

  .right-top {
    padding: 20px 15px 7px 15px;
    display: flex;
    justify-content: space-between;
    color: #303133;
    box-sizing: border-box;
    line-height: 20px;
    background: #fff;
  }
  .right-content {
    color: #303133;
    overflow-y: auto;
    height: 89%;
  }
  .contact-li {
    padding: 0 12px 0 16px;
    margin-top: 4px;
    &:hover {
      background: #f7f8fa;
    }
    &:first-child {
      margin-top: 0;
    }
    .li-cell {
      border-radius: 2px;
      line-height: 32px;
      display: inline-flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      font-weight: bolder;
      i {
        width: 20px;
        height: 20px;
        border-radius: 10px;
        cursor: pointer;
        font-size: 12px;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        &:hover {
          background: #e5e6eb;
        }
      }
    }
  }
  .contact-li + .contact-li {
    margin-top: 4px;
  }
}
.checkBoxContainer {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  .el-checkbox + .el-checkbox {
    margin: 0;
  }
}
</style>
