<!-- banner管理 -->
<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="content_top bg-scroll">
        <type-form
          ref="typeFormRef"
          :businessList="businessList"
          @action="submitFormData"
          @changeType="changeType"></type-form>
        <div class="ability_select">
          <div class="title">
            <span>已选择能力（{{ selectedItemList.length }}/9）</span>
            <el-tooltip class="box-item" effect="light" content="最少需选择6个能力" placement="top">
              <bg-icon icon="#bg-ic-circle-warning" style="color: #7784a6"></bg-icon>
            </el-tooltip>
          </div>
          <div class="select_arr">
            <ability-list
              :list="selectedItemList"
              :flag="true"
              @openBox="openDialog"
              @deleteItem="deleteItem"
              @move="move"></ability-list>
          </div>
        </div>
        <div class="state_box">
          <span>是否启用</span>
          <bg-switch :labels="['否', '是']" :values="[0, 1]" v-model="formData.state"></bg-switch>
        </div>
      </div>
      <div class="content_bottom">
        <div>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      class="select_dialog"
      title="选择能力"
      v-model="selectDialog"
      width="1220px"
      :before-close="cancelSelectDialog">
      <div class="select_box">
        <div class="topFilter">
          <div class="right">
            <el-select
              v-model="dialogFilter.openness"
              placeholder="请选择开放程度"
              style="width: 240px"
              multiple
              collapse-tags>
              <el-option
                v-for="(item, index) in typeList"
                :key="'typeList' + index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-cascader
              v-model="dialogFilter.organization_id"
              :options="orgList"
              placeholder="请选择组织"
              :props="{
                expandTrigger: 'hover',
                label: 'name',
                value: 'id',
                multiple: true,
                emitPath: false,
                checkStrictly: true,
                children: 'Child',
              }"
              :clearable="true"
              collapse-tags
              style="width: 240px">
              <template #default="{ data }">
                <span>{{ data.name }}</span>
              </template>
            </el-cascader>
            <el-input
              v-model.trim="dialogFilter.keyword"
              placeholder="请输入能力/开发商名称"
              style="width: 240px"
              :prefix-icon="Search" />
            <el-button type="primary" @click="searchAction">查询</el-button>
            <el-button type="default" @click="clearAction">重置</el-button>
          </div>
        </div>
        <div class="table_box">
          <div class="collation">
            <div>
              <span
                class="collation-text"
                :class="{ current: dialogFilter.collation == item.value }"
                v-for="(item, index) in collationArr"
                :key="'collationArr' + index"
                @click="changeCollation(item.value)"
                >{{ item.name }}</span
              >
            </div>
            <div>
              <span>已选择</span>
              <span class="num">（{{ toBeAddedItemList.length }}/9）</span>
              <span>项</span>
              <span class="can_click_text" @click="clearSelection">清空</span>
            </div>
          </div>
          <div class="user_table bg-scroll">
            <ability-list
              :list="list"
              :loading="abilityLoading"
              :flag="false"
              @change-selected-list="changeSelectedList"></ability-list>
          </div>
        </div>
      </div>
      <template v-slot:footer>
        <bg-pagination
          :page="dialogFilter.page"
          :size="dialogFilter.limit"
          :total="total"
          @change-page="changePage"
          @change-size="changeSize"
          :pageSizes="[15, 30, 50]">
        </bg-pagination>
        <div class="apaas_button">
          <el-button type="default" @click="cancelSelectDialog">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { reactive, toRefs, ref, onBeforeMount, nextTick } from "vue";
import axios from "../../../../../request/http.js";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import typeForm from "./type-form.vue";
import abilityList from "@/components/ability-list.vue";
const router = useRouter();
const route = useRoute();
const typeFormRef = ref(null);
const state = reactive({
  formData: {
    business_type_id: "",
    logo: [],
    state: 1,
  },
  selectedItemList: [],
  selectDialog: false,
  dialogFilter: {
    openness: [],
    organization_id: [],
    keyword: "",
    limit: 15,
    page: 1,
    collation: 0,
  },
  orgList: [],
  typeList: [],
  total: 0,
  collationArr: [
    {
      name: "综合排序",
      value: 0,
    },
    {
      name: "最新更新",
      value: 1,
    },
    {
      name: "最高人气",
      value: 2,
    },
    {
      name: "最好评价",
      value: 3,
    },
  ],
  businessList: [],
  list: [],
  abilityLoading: false,
  toBeAddedItemList: [],
});

const getDetail = (id) => {
  axios
    .get(`/apaas/system/v5/recommend/ability/detail/${id}`)
    .then((res) => {
      if (res.data.code == 200) {
        const data = res.data.data;
        typeFormRef.value.setForm({
          business_type_id: data.business_type_id,
          logo: data.logo ? [{ url: data.logo }] : [],
        });
        state.selectedItemList = [];
        state.toBeAddedItemList = [];
        state.formData.state = data.state;
        state.formData.business_type_id = data.business_type_id;
        state.selectedItemList = data.ability_list || [];
        state.selectedItemList.forEach((e, i) => {
          e.canDown = true;
          e.canUp = true;
          if (i == 0) {
            e.canUp = false;
          }
          if (i == state.selectedItemList.length - 1) {
            e.canDown = false;
          }
        });
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

const getOrgList = () => {
  axios.get(`/apaas/system/v5/org/tree`).then((res) => {
    if (res.data.code == 200) {
      state.orgList = res.data.data || [];
    } else {
      ElMessage.error(res.data.data);
    }
  });
}; // 获取组织列表

const changeType = (val) => {
  state.formData.business_type_id = val;
  state.selectedItemList = [];
  state.toBeAddedItemList = [];
};
const getAbilityList = () => {
  state.abilityLoading = true;
  let params = {
    ...state.dialogFilter,
    business_type: state.formData.business_type_id,
  };
  params.organization_id =
    params.organization_id && params.organization_id.length > 0
      ? params.organization_id.join(",")
      : "";
  params.openness = params.openness && params.openness.length > 0 ? params.openness.join(",") : "";

  axios.get(`/apaas/system/v5/recommend/ability/list`, { params }).then((res) => {
    if (res.data.code == 200) {
      let selecteItemIdList = state.selectedItemList.map((e) => e.id);
      state.list = res.data.data.ability_list || [];
      state.list.forEach((item) => {
        if (selecteItemIdList.indexOf(item.id) > -1) {
          item.isSelected = true;
        }
      });
      state.total = res.data.data.ability_total;
    }
    state.abilityLoading = false;
  });
};

const openDialog = () => {
  state.selectDialog = true;
  clearAction();
};

const deleteItem = (item) => {
  let selecteItemIdList = state.selectedItemList.map((e) => e.id);
  state.selectedItemList.splice(selecteItemIdList.indexOf(item.id), 1);

  moveAbleChanging();
};

const move = (temp) => {
  let id = temp.item.id;
  let index = null;
  state.selectedItemList.forEach((e, i) => {
    if (e.id == id) {
      index = i;
    }
  });
  if (temp.type == 1) {
    state.selectedItemList[index] = state.selectedItemList[index + 1];
    state.selectedItemList[index + 1] = temp.item;
  } else {
    state.selectedItemList[index] = state.selectedItemList[index - 1];
    state.selectedItemList[index - 1] = temp.item;
  }
  state.selectedItemList.forEach((e, i) => {
    if (e != "") {
      e.canDown = true;
      e.canUp = true;
      if (i == 0) {
        e.canUp = false;
      }
      if (i == state.selectedItemList.length - 1) {
        e.canDown = false;
      }
    }
  });
};
const changePage = (val) => {
  state.dialogFilter.page = val;
  getAbilityList();
};

const changeSize = (val) => {
  state.dialogFilter.limit = val;
  changePage(val);
};

const changeCollation = (val) => {
  state.dialogFilter.collation = val;
  changePage(val);
};

const clearSelection = () => {
  state.toBeAddedItemList = [];
  state.list = [];
};
const searchAction = () => {
  changePage(1);
};

const clearAction = () => {
  state.dialogFilter = {
    openness: [],
    organization_id: [],
    keyword: "",
    collation: 0,
    limit: 15,
  };
  changePage(1);
};

const changeSelectedList = (item, checked) => {
  if (checked) {
    state.toBeAddedItemList.push(item);
  } else {
    let _toBeAddedItemIdList = state.toBeAddedItemList.map((e) => e.id);
    state.toBeAddedItemList.splice(_toBeAddedItemIdList.indexOf(item.id), 1);
  }
  moveAbleChanging();
};

const moveAbleChanging = () => {
  state.selectedItemList.forEach((e, i) => {
    e.canDown = true;
    e.canUp = true;
    if (i == 0) {
      e.canUp = false;
    }
    if (i == state.selectedItemList.length - 1) {
      e.canDown = false;
    }
  });
};

const submit = () => {
  typeFormRef.value.submitForm();
};

const cancelSelectDialog = () => {
  state.selectDialog = false;
  clearSelection();
};

const confirm = () => {
  if (
    state.toBeAddedItemList.length > 9 ||
    state.selectedItemList.length + state.toBeAddedItemList.length > 9
  ) {
    ElMessage.error("最多可选择9个能力");
    return;
  }
  const _newItemList = [];
  state.toBeAddedItemList.forEach((toBeAddedItem) => {
    const hasItem = state.selectedItemList.some(
      (selectedItem) => toBeAddedItem.id === selectedItem.id
    );
    if (!hasItem) {
      _newItemList.push(toBeAddedItem);
    }
  });
  state.selectedItemList.push(..._newItemList);
  state.toBeAddedItemList.length = 0;
  moveAbleChanging();
  clearSelection();
  state.selectDialog = false;
};

const submitFormData = (data) => {
  if (state.selectedItemList.length < 6) {
    ElMessage.error("最少选择6个能力");
    return;
  }
  if (data) {
    Object.assign(state.formData, data);
    if (route.query.id) {
      // 编辑
      let abilitys = [];
      state.selectedItemList.forEach((e) => {
        abilitys.push(e.ability_id);
      });
      let params = {
        ...state.formData,
        id: +route.query.id,
        abilitys: abilitys,
      };
      delete params.business_type_id;
      params.logo = params.logo && params.logo.length > 0 ? params.logo[0].url : "";
      axios.post(`/apaas/system/v5/recommend/ability/update`, params).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          router.go(-1);
        } else {
          ElMessage.error(res.data.data);
        }
      });
    } else {
      let abilitys = [];
      state.selectedItemList.forEach((e) => {
        abilitys.push(e.ability_id);
      });
      let params = {
        ...state.formData,
        abilitys: abilitys,
      };
      params.logo = params.logo && params.logo.length > 0 ? params.logo[0].url : "";
      axios.post(`/apaas/system/v5/recommend/ability/add`, params).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          router.go(-1);
        } else {
          ElMessage.error(res.data.data);
        }
      });
    }
  }
};

const cancel = () => {
  router.go(-1);
};

const getTypeList = () => {
  axios.get("/apaas/system/v5/dictionary/alllist").then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data || [];
      data.forEach((e) => {
        if (e.classify_id == "eb9c7d70-c123-42b7-8e61-dde1b022b669") {
          state.businessList = e.list || [];
        }
        if (e.classify_id == "949a1138-4995-464e-97a9-424d097eb271") {
          state.typeList = e.list || [];
        }
      });
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

onBeforeMount(() => {
  getTypeList();
  getOrgList();
  if (route.query.id) {
    getDetail(route.query.id);
  }
});

const {
  formData,
  selectedItemList,
  selectDialog,
  dialogFilter,
  typeList,
  total,
  orgList,
  collationArr,
  list,
  abilityLoading,
  toBeAddedItemList,
  businessList,
} = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    flex-grow: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    margin: 0 0 16px;
    position: relative;
    height: calc(100% - 62px);
    // padding: 24px;
    .content_top {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding: 30px 40px 20px;
      .ability_select {
        .title {
          font-size: 14px;
          color: #202531;
          margin-bottom: 6px;
          &::before {
            content: "*";
            color: var(--el-color-danger);
            margin-right: 4px;
          }
        }
        .select_arr {
          width: 1216px;
          transform: translateX(-16px);
          // .empty_card {
          //   cursor: pointer;
          //   width: 384px;
          //   height: 242px;
          //   border: 1px dashed #dadee7;
          //   border-radius: 4px;
          //   margin-bottom: 24px;
          //   color: #dadee7;
          //   text-align: center;
          //   line-height: 242px;
          //   font-size: 48px;
          //   font-weight: 100;
          // }
        }
      }
      .state_box {
        font-size: 14px;
        span {
          margin-right: 16px;
        }
      }
    }
    .content_bottom {
      height: 68px;
      line-height: 68px;
      text-align: right;
      padding: 0 20px;
      border-top: 1px solid #e6e9ef;
      .el-button {
        width: 92px;
      }
    }
  }
  .select_dialog {
    .select_box {
      width: 100%;
      height: 680px;
      .topFilter {
        height: 68px;
        padding: 16px;
        border-bottom: 1px solid #e6e9ef;
        display: flex;
        font-size: 14px;
        align-items: center;
        flex-direction: row-reverse;
        // .left {
        //   width: 240px;
        //   padding-left: 15px;
        //   color: #404a62;
        //   .num {
        //     color: #202531;
        //     font-weight: 700;
        //     margin: 0 3px;
        //   }
        // }
        .right {
          width: 912px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .el-button {
            margin: 0;
            width: 64px;
          }
        }
      }
      .table_box {
        padding: 10px 0;
        height: calc(100% - 68px);
        background-color: #f8f9fb;
        .collation {
          width: 100%;
          display: flex;
          justify-content: space-between;
          padding: 6px 16px 16px;
          font-size: 14px;
          color: #202531;

          .collation-text {
            font-size: 14px;
            color: #404a62;
            margin-right: 32px;
            position: relative;
            cursor: pointer;

            &::after {
              content: "";
              display: block;
              position: absolute;
              top: 2px;
              right: -16px;
              width: 1px;
              cursor: auto;
              height: 16px;
              background-color: #cbced7;
            }

            &:nth-last-of-type(1)::after {
              display: none;
            }
          }
          .current {
            color: #3759be !important;
          }
          .can_click_text {
            margin-left: 24px;
          }
        }
        .user_table {
          max-height: calc(100% - 31px);
          // padding: 0 16px;
          // padding-left: 16px;
        }
      }
    }
    .bg-pagination {
      float: left;
      margin-top: 0;
    }
  }
}
</style>
<style>
.select_dialog {
  margin-top: 8vh;
}
.select_dialog .el-dialog__body {
  padding: 0;
}
.select_dialog .el-dialog__footer {
  padding: 16px;
}
</style>
