<template>
    <div class="layout-card">
        <div class="layout-card-item">
            <template v-if="selectable">
                <!--<div class="layout-card-selectAll" v-if="selectable && multiple">-->
                <!--<Checkbox-->
                <!--:indeterminate="indeterminate"-->
                <!--@change="onCheckAllChange"-->
                <!--:checked="checkAll"-->
                <!--&gt;-->
                <!--全选-->
                <!--</Checkbox>-->
                <!--</div>-->
                <div class="layout-card-checkbox-group" v-if="cloneDataSource.length > 0">
                    <template v-for="item in cloneDataSource" class="layout-card-checkbox-group">
                        <div class="ant-checkbox-group" v-if="isColumn(item) === 'column'">
                            <div class="ant-checkbox-group-item">
                                <Checkbox
                                        @change="onChangeBoxChecked"
                                        :value="item.key"
                                        :checked="item.checked"
                                        style="width: 80%;"
                                >
                                    {{item.name}}
                                </Checkbox>
                                <span class="layout-tree-organize"
                                      @click.prevent.stop="getDownTreeLoad($event,item)"
                                >
                                    <Divider type="vertical"/>
                                    <Icon type="cluster"/>
                                    <!--下级-->
                                    <i class="cluster-text">{{nextText.next[language]}}</i>
                                </span>
                            </div>
                        </div>
                        <div v-else-if="isColumn(item) === 'more'"
                             :key="item.key"
                             class="ant-checkbox-group">
                            <div class="ant-checkbox-group-item"
                                 @click="itemClickMore($event,item)" style="text-align: center;">
                                <span style="color: #339cfe;">{{item.name}}</span>
                                <div class="clearfix"></div>
                            </div>
                        </div>
                        <div v-else-if="isColumn(item) === 'avatar'">
                            <Checkbox @change="onChangeBoxChecked">{{item.name}}</Checkbox>
                            <Avatar class="layout-avatar">
                                {{item.value ? item.value.substring(0,1) : '佚名'}}
                            </Avatar>
                            <span class="layout-avatar-span">{{item.value}}</span>
                        </div>
                        <div v-else>
                            <span class="layout-avatar-span">No Data</span>
                        </div>
                    </template>
                </div>
                <div v-else class="empty-data">暂无数据</div>
                <!--<Empty v-else/>-->
            </template>
            <template v-else>
                <div class="layout-card-checkbox-group" v-if="dataSource.length > 0">
                    <template v-for="slotScope in dataSource">
                        <div v-if="isColumn(slotScope) === 'column'"
                             :key="slotScope.key"
                             class="ant-checkbox-group">
                            <div :class="['ant-checkbox-group-item','i-animation-color',`i-${slotScope.key}`]"
                                 @click="itemClick($event,slotScope)">
                                <span>{{slotScope.name}}</span>
                                <span class="layout-tree-organize"
                                      @click.prevent.stop="getDownTreeLoad($event,slotScope)">
                                      <Divider type="vertical"/>
                                      <slot name="next">
                                          <Icon type="cluster"/>
                                      </slot>
                                        <!--下级-->
                                      <i style="font-style: normal;" class="cluster-text">{{nextText.next[language]}}</i>
                                  </span>
                                <div class="clearfix"></div>
                            </div>
                        </div>
                        <div v-else-if="isColumn(slotScope) === 'more'"
                             :key="slotScope.key"
                             class="ant-checkbox-group">
                            <div :class="['ant-checkbox-group-item','i-animation-color',`i-${slotScope.key}`]"
                                 @click="itemClickMore($event,slotScope)" style="text-align: center;">
                                <span style="color: #339cfe;">{{slotScope.name}}</span>
                                <div class="clearfix"></div>
                            </div>
                        </div>
                        <div v-else-if="isColumn(slotScope) === 'avatar'" :key="slotScope.key"
                             class="ant-checkbox-group"
                             @click="getAvatarDownTreeLoad($event,slotScope)">
                            <div :class="['ant-checkbox-group-item','i-animation-color',`i-${slotScope.key}`]"
                                 style="display: flex;align-items: center">
                                <Avatar :src="slotScope.avatar?slotScope.avatar:''" class="layout-avatar">
                                    {{slotScope.value ? slotScope.value.substring(0,1) :'佚名'}}
                                </Avatar>
                                <div v-if="custom" style="display: inline-block;margin-left: 8px">
                                    <slot name="custromRender" :scope="slotScope"></slot>
                                </div>
                                <span v-else class="layout-avatar-span">{{slotScope.value}}</span>
                            </div>
                        </div>
                        <div v-else>No Data</div>
                    </template>
                </div>
                <div v-else class="empty-data">暂无数据</div>
                <slot name="lazys"></slot>
                <!--<Empty v-else/>-->
            </template>
        </div>
    </div>
</template>

<script>
  import {
    Checkbox,
    Icon,
    Divider,
    Avatar,
    Tag
  } from 'ant-design-vue';
  import $ from 'jquery-slim';
  import {cloneDeep} from 'lodash';
  const nextText={
    next: {
      zh_CN: "下级",
      en_GB: "Sub",
    },
  };
  export default {
    name: 'layout-card',
    components: {
      Checkbox,
      Icon,
      Divider,
      Avatar,
      CheckboxGroup: Checkbox.Group,
      Tag
    },
    props: {
      dataSource: Array,
      selectable: Boolean,
      value: Array,
      multiple: Boolean,
      radio: Boolean,
      noArray: Boolean,
      isObject: Boolean,
      backField: Array,
      custom: Boolean,
      htmlFormatter: Function
    },
    data() {
      return {
        checkedList: [],
        newResult: [],
        originDataSource: {}, // 所有的源数据
        currentPageData: {},
        cloneDataSource: null,
        nextText
      };
    },
    watch: {
      value: { // value是选中key，type 是array
        immediate: true,
        handler(value) {
          // console.log('选中的值:', value);
          if (this.multiple) {
            this.seriaLizationData();
            this.checkedList = value;
          }
          this.checkedList = value;
          this.seriaLizationData();
          return value;
        }
      },
      selectable: {
        handler(value) {
          if (value) {
            this.seriaLizationData();
          }
        },
        immediate: true
      },
      dataSource(nv, ov) {
        if (JSON.stringify(nv) === JSON.stringify(ov)) return false;
        if (this.selectable || this.radio || this.multiple) {
          this.seriaLizationData(); // 生成新的树数据
        }
        return nv;
      }
    },
    computed: {
      language() {
        return JSON.parse(window.localStorage[window.$project]).setting.language || "zh_CN";
      }
    },
    methods: {
      isColumn(info) {
        return this.htmlFormatter(info);
      },
      async onChangeBoxChecked(e) {
        const value = e.target.value;
        /* 单选 */
        const noArrayIsObject = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [value];
            // // console.log('noArrayIsObject:', this.originDataSource[value]);
            this.$emit('on-change', this.originDataSource[value]);
          } else { // 取消选中
            this.checkedList = [];
            this.$emit('on-change', {});
          }
        };
        const noArrayIsString = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [value];
            // // console.log('noArrayIsString:', value);
            this.$emit('on-change', value);
          } else { // 取消选中
            this.checkedList = [];
            this.$emit('on-change', '');
          }
        };
        const isArrayIsObject = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [value];
            // // console.log('isArrayIsObject:', [this.originDataSource[value]]);
            this.$emit('on-change', [this.originDataSource[value]]);
          } else { // 取消选中
            this.checkedList = [];
            this.$emit('on-change', []);
          }
        };
        const isArrayIsString = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [value];
            // // console.log('isArrayIsObject:', [value]);
            this.$emit('on-change', [value]);
          } else { // 取消选中
            this.checkedList = [];
            this.$emit('on-change', []);
          }
        };
        /* 多选 */
        const mulIsArrayIsObject = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [...this.checkedList, value];
            let backFiledArray = [];
            this.checkedList.map(key => {
              if (this.originDataSource[key]) {
                backFiledArray.push(this.originDataSource[key]);
              }
            });
            // // console.log('mulIsArrayIsObject:', backFiledArray);
            this.$emit('on-change', backFiledArray);
          } else { // 取消选中
            let index = this.checkedList.indexOf(value);
            if (index > -1) {
              this.checkedList.splice(index, 1);
              let backFiledArray = [];
              this.checkedList.map(key => {
                if (this.originDataSource[key]) {
                  backFiledArray.push(this.originDataSource[key]);
                }
              });
              this.$emit('on-change', backFiledArray);
            }
          }
        };
        const mulIsArrayIsString = async () => {
          if (e.target.checked) { // 选中
            this.checkedList = [...this.checkedList, value];
            // // console.log('mulIsArrayIsString:', this.checkedList);
            this.$emit('on-change', this.checkedList);
          } else { // 取消选中
            let index = this.checkedList.indexOf(value);
            if (index > -1) {
              this.checkedList.splice(index, 1);
              this.$emit('on-change', this.checkedList);
            }
          }
        };
        if (this.radio) {
          // console.log('单选');
          if (this.noArray) { // 不要数组
            if (this.isObject) { // 要对象不要字符串
              await noArrayIsObject();
              this.seriaLizationData();
            } else { // 不要对象，要字符串
              await noArrayIsString();
              this.seriaLizationData();
            }
          } else { // 返回数组
            if (this.isObject) { // 对象数组
              await isArrayIsObject();
              this.seriaLizationData();
            } else { // 字符数组
              await isArrayIsString();
              this.seriaLizationData();
            }
          }
        }
        if (this.multiple) {
          // console.log('多选');
          if (this.isObject) { // 数组用对象包住
            await mulIsArrayIsObject();
            this.seriaLizationData();
          } else { // 数组直接返回字符串
            await mulIsArrayIsString();
            this.seriaLizationData();
          }
        }
      },
      /* 序列化渲染数据 */
      seriaLizationData() {
        const datas = cloneDeep(this.dataSource);
        const checklist = cloneDeep(this.checkedList);
        /* 新增序列化处理 */
        datas.forEach(v => {
          v.value = v.key;
          v['checked'] = checklist.indexOf(v.key) > -1;
          this.originDataSource[v.key] = v;
        });
        this.cloneDataSource = datas;
        // // console.log('============>所有的源数据', this.originDataSource);
      },
      getDownTreeLoad(e, info) {
        e.preventDefault();
        e.stopPropagation();
        this.$emit('click', info);
      },
      getAvatarDownTreeLoad(e, key) {
        e.preventDefault();
        e.stopPropagation();
        this.$emit('change', e, key);
      },
      itemClick(e, info) {
        e.stopPropagation();
        this.$emit('change', e, info);
        this.addClassByKey(e.target);
      },
      itemClickMore(e, info) {
        e.stopPropagation();
        this.$emit('more', info);
      },
      addClassByKey(_self) {
        $('.i-animation-active').removeClass('i-animation-active');
        $(_self).addClass('i-animation-active');
      }
    }
  };
</script>
