<!-- 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>已选择能力（{{ selectArrNew.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="selectArr"
              :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">
      <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">（{{ selectArrNew.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" @changeCheck="changeCheck"></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="selectDialog = false">取 消</el-button>
          <el-button type="primary" @click="conform">确 定</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,
  },
  selectArr: ["", "", "", "", "", "", "", "", ""],
  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: [],
  selectArrNew: [],
});

const getDetail = (id) => {
  axios
    .get(`/apaas/system/v5/recommend/ability/detail/${id}`)
    .then((res) => {
      if (res.data.code == 200) {
        const data = res.data.data;
        console.log(data);
        typeFormRef.value.setForm({
          business_type_id: data.business_type_id,
          logo: data.logo ? [{ url: data.logo }] : [],
        });
        state.selectArr = [];
        state.selectArrNew = [];
        state.formData.state = data.state;
        state.formData.business_type_id = data.business_type_id;
        state.selectArrNew = data.ability_list || [];
        state.selectArrNew.forEach((e, i) => {
          e.canDown = true;
          e.canUp = true;
          if (i == 0) {
            e.canUp = false;
          }
          if (i == state.selectArrNew.length - 1) {
            e.canDown = false;
          }
        });
        state.selectArr.push(...state.selectArrNew);
        for (var i = 0; i < 9 - state.selectArrNew.length; i++) {
          state.selectArr.push("");
        }
      } 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.selectArr = ["", "", "", "", "", "", "", "", ""];
  state.selectArrNew = [];
};
const getAbilityList = () => {
  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) {
      state.list = res.data.data.ability_list || [];
      state.selectArrNew = [];
      state.total = res.data.data.ability_total;
      nextTick(() => {
        state.list.forEach((e) => {
          e.checked = false;
          state.selectArr.forEach((k) => {
            if (k.id) {
              if (e.id == k.id) {
                e.checked = true;
                state.selectArrNew.push(e);
              }
            }
          });
        });
      });
    }
  });
};

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

const deleteItem = (item) => {
  changeCheck(item, true);
};

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

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

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

const clearSelection = () => {
  state.list.forEach((e) => {
    e.checked = false;
  });
  state.selectArrNew = [];
};
const searchAction = () => {
  changePage(1);
};

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

const changeCheck = (item, deleteFlag) => {
  let arr = state.selectArrNew.map((e) => e.id) || [];
  if (arr.indexOf(item.id) > -1) {
    state.selectArrNew.splice(arr.indexOf(item.id), 1);
  } else {
    state.selectArrNew.push(item);
  }
  state.selectArrNew.forEach((e, i) => {
    e.canDown = true;
    e.canUp = true;
    if (i == 0) {
      e.canUp = false;
    }
    if (i == state.selectArrNew.length - 1) {
      e.canDown = false;
    }
  });
  if (deleteFlag) {
    conform();
  }
};
const submit = () => {
  typeFormRef.value.submitForm();
};

const conform = () => {
  if (state.selectArrNew.length > 9) {
    ElMessage.error("最多可选择9个能力");
    return;
  }
  state.selectArr = JSON.parse(JSON.stringify(state.selectArrNew));
  if (state.selectArr.length < 9) {
    let arr = [];
    for (var i = 0; i < 9 - state.selectArr.length; i++) {
      arr.push("");
    }
    state.selectArr.push(...arr);
  }
  state.selectDialog = false;
};

const submitFormData = (data) => {
  if (state.selectArrNew.length < 6) {
    ElMessage.error("最少选择6个能力");
    return;
  }
  if (data) {
    Object.assign(state.formData, data);
    console.log(state.formData);
    if (route.query.id) {
      // 编辑
      let abilitys = [];
      state.selectArrNew.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.selectArrNew.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,
  selectArr,
  selectDialog,
  dialogFilter,
  typeList,
  total,
  orgList,
  collationArr,
  selection,
  list,
  selectArrNew,
  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: 80px;
}
.el-dialog .el-dialog__body {
  padding: 0;
}
.el-dialog .el-dialog__footer {
  padding: 16px;
}
</style>
