<template>
  <div>
    <el-dialog v-model="pushDialog" append-to-body title="上传素材" destroy-on-close width="75%" @open="dialogOpen" :close-on-click-modal="false" :before-close="handleDialogClose">
      <div class="dialog-container">
        <div class="dialog-left">
          <template v-for="item in pushFiles">
            <div class="left-item">
              <div class="image">
                <el-image referrerpolicy="no-referrer" :src="item.thumb" style="object-fit: contain; width: 150px; height: 150px" fit="contain"></el-image>
              </div>
              <el-tooltip class="box-item" effect="dark" :content="item.file_name" placement="top-start">
                <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ item.file_name }}</span>
              </el-tooltip>
            </div>
          </template>
        </div>
        <div class="dialog-right">
          <div class="right-item">
            <el-icon style="font-size: 20px; margin-right: 10px"><Grid /></el-icon>
            <el-button @click="selectClaFun">添加分类</el-button>
          </div>
          <div class="add-item">
            <el-empty description="未选择分类" v-if="file_cla_list.length == 0"></el-empty>
            <div style="margin-top: 10px" v-else>
              <template v-for="item in file_cla_list">
                <el-tag @close="handleFileClose(item)" closable style="margin-right: 10px; margin-bottom: 5px">{{ item.title }}</el-tag>
              </template>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadSubmit">确 定</el-button>
          <el-button @click="handleDialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="selectClaDialog" title="添加分类" width="40%">
      <div class="cla-container" v-if="Object.keys(cla_list).length > 0">
        <div class="cla-left">
          <div class="cla-tree" :class="show_child ? 'show-child' : ''">
            <div class="cla-inner">
              <div class="cla-top-tree">
                <div class="cla-top-tree-item">
                  <span>分类</span>
                  <el-icon class="tree-item-add" @click="createClaBtn(false, 0)"><Plus /></el-icon>
                </div>
                <template v-for="(item, key) in cla_list">
                  <div class="cla-top-tree-item item-info" @click="handleChild(item)">
                    <div class="item-container">
                      <el-icon style="margin-top: 5px"><ArrowLeft style="transform: rotate(-45deg)" /></el-icon>
                      <span>{{ item.title }}</span>
                    </div>
                    <div class="item-container">
                      <div style="position: relative">
                        <el-icon @click.stop="item.visible = true"><More style="transform: rotate(90deg); margin-right: 5px" /></el-icon>
                        <div class="popup-container" v-if="item.visible">
                          <span class="popup-item" @click.stop="hanldeChangeName(item)">重命名</span>
                          <span class="popup-item" @click.stop="hanldeDeleteCla(item)" v-if="Object.keys(cla_list).length > 1">删除</span>
                        </div>
                      </div>
                      <el-icon><ArrowRightBold /></el-icon>
                    </div>
                  </div>
                </template>
              </div>
              <div class="cla-child-tree">
                <div class="cla-top-tree-item">
                  <div class="item-container">
                    <el-icon class="tree-item-add" @click="backCla"><ArrowLeft /></el-icon>
                    <span>{{ parent_cla_id.title }}</span>
                  </div>
                  <el-icon class="tree-item-add" @click="createClaBtn(false, 0)"><Plus /></el-icon>
                </div>
                <template v-if="parent_cla_id.children && parent_cla_id.children.length > 0">
                  <template v-for="(item, key) in parent_cla_id.children">
                    <div class="cla-top-tree-item item-info">
                      <div class="item-container" style="padding-left: 10px">
                        <el-checkbox v-model="item.checked" style="margin-right: 5px; height: unset" @change="handleChange(item)"></el-checkbox>
                        <span>{{ item.title }}</span>
                      </div>
                      <div class="item-container">
                        <div style="position: relative">
                          <el-icon @click.stop="item.visible = true"><More style="transform: rotate(90deg); margin-right: 5px" /></el-icon>
                          <div class="popup-container" v-if="item.visible">
                            <span class="popup-item" @click.stop="hanldeChangeName(item)">重命名</span>
                            <span class="popup-item" @click.stop="hanldeDeleteCla(item)">删除</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </template>
                <template v-else>
                  <el-empty description="未选择分类"></el-empty>
                  <div class="empty-container">
                    <span>
                      您还没有分类，请先
                      <span class="create-cla-btn" @click="createClaBtn(false, 0)">创建分类</span>
                    </span>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div class="cla-right">
          <div>{{ cla_select_list.length }}个分类</div>
          <div style="margin-top: 10px">
            <template v-for="item in cla_select_list">
              <el-tag @close="handleClose(item)" closable style="margin-right: 10px; margin-bottom: 5px">{{ item.title }}</el-tag>
            </template>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="未选择分类"></el-empty>
        <div class="empty-container">
          <span>
            您还没有分类，请先
            <span class="create-cla-btn" @click="createClaBtn(false, 0)">创建分类</span>
          </span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sbumitFileCla">确 定</el-button>
          <el-button @click="selectClaDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="createClaDialog" title="创建分类" width="20%">
      <div>
        <span style="margin-bottom: 10px; display: block">分类名称</span>
        <el-input v-model="cla_option.name" placeholder="请输入分类名称" clearable></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCreateCategory">确 定</el-button>
          <el-button @click="createClaDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { createCategory, listApolloByTeam, updateCategory, deleteCategory } from '@/api/zhihui/index.js';
import { ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance();
const emits = defineEmits(['update:pushDialog', 'updateEnd', 'dialogClose']);
const props = defineProps({
  pushDialog: {
    type: Boolean,
    default: false,
  },
  belong: {
    type: String,
  },
  name: {
    type: String,
  },
  type: {
    type: String,
    default: 'template',
  },
  pushFiles: {
    type: Array,
    default: [],
  },
  inputIds: {
    type: Array,
    default: [],
  },
});

const { pushDialog, belong, name, type, pushFiles, inputIds } = toRefs(props);
const selectClaDialog = ref(false); //选择分类弹窗
const createClaDialog = ref(false); //创建分类
const cla_list = ref({}); //分类
const cla_select_list = ref([]); //选中的分类
const show_child = ref(false);
const cla_option = ref({
  level: 0,
  name: '',
  teamId: belong.value,
  type: '',
});
const original_cla_list = ref([]);
const parent_cla_id = ref({}); //选中父级
const file_cla_list = ref([]);

function handleChange(value) {
  if (cla_select_list.value.indexOf(value) == -1) {
    cla_select_list.value.push(value);
  } else {
    cla_select_list.value = cla_select_list.value.filter(item => item !== value);
  }
  proxy.$forceUpdate();
}
function handleClose(value) {
  value.checked = !value.checked;
  cla_select_list.value = cla_select_list.value.filter(item => item !== value);
  proxy.$forceUpdate();
}
function handleDialogClose() {
  cla_select_list.value = [];
  file_cla_list.value = [];
  emits('update:pushDialog', false);
  emits('dialogClose');
}
function sbumitFileCla() {
  file_cla_list.value = cla_select_list.value;
  selectClaDialog.value = false;
}
function handleFileClose(item) {
  file_cla_list.value = file_cla_list.value.filter(value => value !== item);
}

//点击按钮创建参数
function createClaBtn(item, level) {
  createClaDialog.value = true;
  cla_option.value = {
    level: level,
    name: '',
    teamId: belong.value,
    type: '',
  };
  if (item) {
    cla_option.value.id = item.value;
  }
}
//转到子类
function handleChild(item) {
  parent_cla_id.value = item;
  show_child.value = !show_child.value;
  if (cla_select_list.value.length > 0) {
    parent_cla_id.value.children.map(i => {
      let list = cla_select_list.value.filter(k => k.value === i.value);
      if (list.length > 0) {
        i.checked = true;
      }
    });
  }
}

function backCla() {
  parent_cla_id.value = {};
  show_child.value = !show_child.value;
}
function delSelectData(option, type = 'update') {
  if (type == 'update') {
    cla_select_list.value.map(item => {
      if (item.value == option.value) {
        item.title = option.name;
      }
    });
    file_cla_list.value.map(item => {
      if (item.value == option.value) {
        item.title = option.name;
      }
    });
  }
  if (type == 'delete') {
    cla_select_list.value = cla_select_list.value.filter(item => item.value !== option.value);
    file_cla_list.value = file_cla_list.value.filter(item => item.value !== option.value);
  }
}
//创建分类
async function handleCreateCategory() {
  if (cla_option.value.value) {
    let data = await updateCategory({ name: cla_option.value.name }, cla_option.value.value);
    if (data.statusCode == 200) {
      createClaDialog.value = false;
      delSelectData(cla_option.value, 'update');
    }
  } else {
    if (parent_cla_id.value.value) {
      cla_option.value.parentId = parent_cla_id.value.value;
    }
    let data = await createCategory(cla_option.value);
    if (data.statusCode == 201) {
      createClaDialog.value = false;
    }
  }
  getCla();
}
//获取分类
async function getCla() {
  if (belong.value) {
    let option = {
      teamId: belong.value,
      type: '',
    };
    let data = await listApolloByTeam(option);
    if (data.statusCode == 200) {
      cla_list.value = {};
      original_cla_list.value = data.data;
      let data_list = {};
      data.data?.map(item => {
        item.checked = false;
        if (!item.parentId) {
          data_list[item.key] = item;
        } else {
          if (!data_list[item.parentId]) {
            data_list[item.parentId] = {};
          }
          if (!data_list[item.parentId]?.children) {
            data_list[item.parentId].children = [];
          }
          data_list[item.parentId].children.push(item);
        }
        Object.keys(data_list).map(k => {
          if (data_list[k].value) {
            cla_list.value[k] = data_list[k];
          }
        });
        if (inputIds.value.length > 0) {
          if (inputIds.value.indexOf(item.value) > -1) {
            cla_select_list.value.push(item);
            file_cla_list.value.push(item);
          }
        }
      });
      if (parent_cla_id.value.value) {
        Object.keys(cla_list.value).map(item => {
          if (item == parent_cla_id.value.value) {
            parent_cla_id.value = cla_list.value[item];
          }
        });
      }
    }
  }
}

function hanldeChangeName(item) {
  cla_option.value = item;
  cla_option.value.name = item.title;
  createClaDialog.value = true;
}
function hanldeDeleteCla(item) {
  ElMessageBox.confirm('是否删除该分类?')
    .then(async () => {
      let data = await deleteCategory({}, item.value);
      if (data.statusCode == 200) {
        delSelectData(item, 'delete');
        if (item.children.length > 0) {
          item.children.map(i => {
            delSelectData(i, 'delete');
          });
        }
      }
    })
    .catch(() => {})
    .finally(() => {
      hidePopup();
      getCla();
    });
}

document.addEventListener('click', hidePopup);
function hidePopup() {
  Object.keys(cla_list.value).map(item => {
    cla_list.value[item].visible = false;
    cla_list.value[item]?.children?.map(i => {
      i.visible = false;
    });
  });
}

function uploadSubmit() {
  let cla_ids = [];
  if (file_cla_list.value.length > 0) {
    file_cla_list.value.map(item => {
      cla_ids.push(item.value);
    });
  }
  cla_select_list.value = [];
  file_cla_list.value = [];
  emits('updateEnd', cla_ids);
}
function selectClaFun() {
  selectClaDialog.value = true;
}
function dialogOpen() {
  getCla();
}
</script>
<style scoped lang="scss">
.dialog-container {
  height: 500px;
  display: flex;
  border-top: solid 1px #e6e6e6;
  > div {
    padding: 20px;
  }
  .dialog-left {
    flex: 3;
    display: flex;
    border-right: solid 1px #e6e6e6;
    .left-item {
      display: flex;
      flex-direction: column;
      margin-left: 5px;
      width: 175px;
      .image {
        background: linear-gradient(45deg, #aeaeae 25%, transparent 0, transparent 75%, #aeaeae 0, #aeaeae), linear-gradient(45deg, #aeaeae 25%, #ccc 0, #ccc 75%, #aeaeae 0, #aeaeae);
        background-position:
          0 0,
          6px 6px;
        background-size: 12px 12px;
        margin-bottom: 3px;
      }
    }
  }
  .dialog-right {
    flex: 1;
    .right-item {
      display: flex;
      align-items: center;
    }
  }
}
.cla-container {
  min-height: 300px;
  display: flex;
  font-size: 16px;
  > div {
    border: solid #e7e7e7 1px;
    padding: 20px;
  }
  .cla-left {
    flex: 1;
    .cla-tree {
      overflow-x: hidden;

      .cla-inner {
        display: flex;
        transition: transform 0.2s linear;
        .cla-top-tree,
        .cla-child-tree {
          flex-shrink: 0;
          min-height: 300px;
          width: 100%;
          .cla-top-tree-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;
            .tree-item-add {
              &:hover {
                background-color: #f1f2f4;
                cursor: pointer;
              }
            }
            .item-container {
              display: flex;
              align-items: center;
            }
          }
          .item-info {
            padding: 10px 10px 10px 0;
            font-size: 14px;
            &:hover {
              background-color: #f1f2f4;
              cursor: pointer;
            }
          }
        }
        .cla-child-tree {
          width: 100%;
          min-height: 300px;
          flex-shrink: 0;
        }
      }
    }
  }
  .cla-right {
    flex: 1;
  }
}
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  span {
    font-size: 14px;
    color: #999;
  }
  .create-cla-btn {
    color: #409eff;
    cursor: pointer;
  }
}
.show-child {
  .cla-inner {
    transform: translateX(-100%);
  }
}
.popup-container {
  z-index: 2;
  position: absolute;
  left: -40px;
  width: 65px;
  background-color: #fff;
  padding: 10px;
  display: flex;
  flex-direction: column;
  box-shadow:
    0 3px 6px -4px rgba(0, 0, 0, 0.12),
    0 6px 16px 0 rgba(0, 0, 0, 0.08),
    0 9px 28px 8px rgba(0, 0, 0, 0.05);
  .popup-item {
    &:hover {
      color: #409eff;
      cursor: pointer;
    }
  }
}
</style>
