<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-04-14 09:50:16
 * @LastEditors: 无尘
 * @LastEditTime: 2020-05-14 18:01:17
 -->
<!--
  <select-group :materialIds="materialIds"  @closeGroup="closeGroup" @submitGroup="submitGroup"></select-group>
  import selectGroup from '@/components/set/select-group.vue';
 -->
<template>
  <el-dialog title="批量操作-移至分组" :visible.sync="dialogVisible" width="485px" :before-close="handleClose">
    <div class="">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="分组" prop="categoryId">
          <!-- <el-select v-model="ruleForm.categoryId" placeholder="请选择">
            <el-option label="未分组" value="-1"></el-option>
            <el-option v-for="item in groupData" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"> </el-option>
          </el-select> -->
          <el-popover placement="bottom" style="min-width: 357px" trigger="click">
            <div class="select-tree-wrap">
              <div class="group-body">
                <div :class="['no-group m-t-10 line-h-32 font-14 color-606266 cursor-pointer', currentCategoryId == '-1' ? 'current-group' : '']" @click="selectNoGroup"><span style="color: transparent;" :class="['color-c0c4cc font-12 cursor-pointer p-l-10 el-icon-caret-bottom el-icon-caret-right']"></span>未分组</div>
                <ul class="group-ul padding-lr-12">
                  <template v-for="(item, index) in groupData">
                    <li class="group-cell" :key="index + 'group'">
                      <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(item)">
                        <span :class="['color-c0c4cc font-12 cursor-pointer', item.children.length ? 'color-c0c4cc' : 'color-transparent', item.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == item.categoryId ? 'current-group' : '']">{{ item.categoryName }}</span>
                      </div>
                      <ul v-if="item.expand" class="p-l-10">
                        <template v-for="(itemTwo, ind) in item.children">
                          <li class="group-cell" :key="ind + 'group'">
                            <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(itemTwo)">
                              <span :class="['font-12 cursor-pointer', itemTwo.children.length ? 'color-c0c4cc' : 'color-transparent', itemTwo.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == itemTwo.categoryId ? 'current-group' : '']">{{ itemTwo.categoryName }}</span>
                            </div>
                            <ul v-if="itemTwo.expand" class="p-l-10">
                              <template v-for="(itemThree, i) in itemTwo.children">
                                <li class="group-cell" :key="i + 'group'">
                                  <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(itemThree)">
                                    <span :class="['font-12 cursor-pointer color-transparent', itemThree.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == itemThree.categoryId ? 'current-group' : '']">{{ itemThree.categoryName }}</span>
                                  </div>
                                </li>
                              </template>
                            </ul>
                          </li>
                        </template>
                      </ul>
                    </li>
                  </template>
                </ul>
              </div>
            </div>
            <div class="flex-column item-cell-select inline-block " slot="reference">
              <div class="depart-item-wrap">
                <div :style="{ width: width }" class="el-select el-select--large depart-item-content">
                  <span v-if="!ruleForm.categoryId" class="font-14 color-c0c4cc" style="display: inline-block;line-height: 32px;color: #c0c4cc;">请选择</span>
                  {{ categoryName }}
                </div>
              </div>
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="toCancel">取消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
export default {
  props: {
    materialIds: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  components: {
    limitInput
  },
  data() {
    return {
      width: '347px',
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      dialogVisible: true,
      groupData: [],
      ruleForm: {
        categoryId: ''
      },
      rules: {
        categoryId: [{ required: true, message: '请选择分组名称', trigger: 'change' }]
      },
      categoryName: '',
      currentCategoryId: '',
      expandArr: []
    };
  },
  methods: {
    toCancel() {
      const that = this;
      that.$emit('closeGroup');
      that.$refs['ruleForm'].resetFields();
    },
    handleClose(done) {
      const that = this;
      that.$emit('closeGroup');
      that.$refs['ruleForm'].resetFields();
    },
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSave();
        }
      });
    }, 300),
    postSave() {
      const that = this;
      const data = {
        categoryId: that.ruleForm.categoryId,
        materialIds: that.materialIds
      };
      postRequest('/haoban-manage3-web/material-batch', data)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.$refs['ruleForm'].resetFields();
            that.$emit('submitGroup');
          } else {
            errMsg.errorMsg(resData);
          }
        })
        .catch(error => {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 选中分组
     */
    selectGroup(item) {
      const that = this;
      item.expand = item.expand ? false : true;
      that.ruleForm.categoryId = item.categoryId;
      that.currentCategoryId = item.categoryId;
      that.categoryName = item.categoryName;
      // 为了保存展开/收起状态，存储数据
      if (item.expand) {
        that.expandArr.push(item.categoryId);
      } else {
        that.expandArr.splice(that.expandArr.indexOf(item.categoryId), 1);
      }
    },
    selectNoGroup() {
      const that = this;
      that.ruleForm.categoryId = '-1';
      that.currentCategoryId = '-1';
      that.categoryName = '未分组';
    },
    /**
     * 简单数组-->父子数组对象
     */
    treeData(data) {
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.categoryId == child.categoryParentId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.children = [];
        }
        return father.categoryParentId == 0; //返回第一层
      });
      console.log('tree:', tree);
      return tree;
    },
    /**
     * 获取数据
     */
    getGroupData(val) {
      const that = this;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest('/haoban-manage3-web/category-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.length) {
              resData.result.forEach(ele => {
                ele.expand = that.expandArr.includes(ele.categoryId) ? true : false;
              });
              that.groupData = that.treeData(resData.result) || [];
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {},
  mounted() {
    const that = this;
    that.getGroupData();
  }
};
</script>
<style lang="less" scoped>
.m-b-20 {
  margin-bottom: 20px;
}
.p-l-18 {
  padding-left: 18px;
}
.bg-ebecf0 {
  background: #ebecf0;
}
.color-afaeae {
  color: #afaeae;
}
.color-c0c4cc {
  color: #c0c4cc;
}
.color-transparent {
  color: transparent;
}
.condition-tips {
  display: inline-block;
  vertical-align: middle;
  line-height: 32px;
}
.p-l-30 {
  padding-left: 30px;
}
.p-l-40 {
  padding-left: 40px;
}
.p-l-55 {
  padding-left: 55px;
}
.p-l-85 {
  padding-left: 85px;
}
.p-r-5 {
  padding-right: 5px;
}
.m-l-20 {
  margin-left: 20px;
}
.line-50 {
  height: 50px;
  line-height: 50px;
}

.line-h-32 {
  line-height: 32px;
}
.select-tree-wrap {
  min-width: 300px;
  max-height: 300px;
  overflow-y: auto;
}
.add-group {
  width: 154px;
  height: 32px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 1);
  border: 1px dashed rgba(192, 196, 204, 1);
  &:hover {
    color: #2f54eb;
    border-color: #2f54eb;
  }
}
.depart-item-content {
  width: 213px;
  height: 32px;
  padding: 0 12px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 2px;
  border: 1px solid #c4c6cf;
  cursor: pointer;
  box-sizing: border-box;
}
.group-body {
  padding: 0 12px;
  .group-ul {
    .group-cell {
      position: relative;
      min-height: 32px;
      line-height: 32px;
      .group-name {
        display: inline-block;
        vertical-align: top;
        max-width: 132px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .group-cell-div {
        &:hover {
          .operate-icon {
            display: inline-block;
          }
          .group-name {
            color: #2f54eb;
          }
        }
      }
    }
  }
  .current-group {
    color: #2f54eb;
  }
}
</style>
