<template>
  <div class="tenant">
    <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
        select: select,
      }"
        :action-list="[
        {
          text: '添加栏目菜单',
          action: () => openModal('add'),
        },
      ]"
        @get-list="getList">

      <template #listType="{ item }">
        {{  getCellColumn(item) }}
      </template>

    </byTable>
    <el-dialog z-index="1100" :title="modalType == 'add' ? '添加栏目菜单' : '编辑栏目菜单'" v-if="dialogVisible" v-model="dialogVisible" width="80%" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <template #subColumn>
          <el-row style="width: 100%;margin-bottom: 10px"   v-for="(row, index) in formData.data.columnMenuSubList" ref="sort">
            <el-col :span="7" >
              <el-form-item
                  :prop="'columnMenuSubList.' + index + '.name'"
                  :rules="rules.subName"
                  prop="name"
                  style="margin: 8px 0 8px 0">
                <el-input v-model="row.name" placeholder="请输入子栏目" :controls="false" />
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item
                  :prop="'columnMenuSubList.' + index + '.status'"
                  :rules="rules.subStatus" style="margin-left: 8px;transform: translateY(8px)"
                  prop="status">
                <el-select clearable v-model="row.status" placeholder="请选择状态" >
                  <el-option v-for="item in enableStatus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item
                  :prop="'columnMenuSubList.' + index + '.sort'"
                  :rules="rules.subSort" style="margin-left: 8px;transform: translateY(8px)"
                  prop="sort">
                <el-input-number v-model="row.sort" placeholder="请输入排序" :precision="0" :max="999"  :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="5" >
              <el-icon style="margin-left: 8px; color: red; cursor: pointer; transform: translateY(10px)" @click="clickDelete(index)"><Delete /></el-icon>
            </el-col>
          </el-row>
          <el-row style="width: 100%">
            <el-row>
              <el-button type="primary" @click="clickAddSubColumn()">添加</el-button>
            </el-row>
          </el-row>
        </template>

        <template #detailsContent>
          <div style="width: 100%" v-if="dialogVisible">
            <TinymceEditor
                :value="formData.data.content"
                @updateValue="updateHandover"
                ref="contentEditor"
            />
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" v-no-double-click="submitForm" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import {computed, nextTick, reactive, ref} from "vue";
import TinymceEditor from "@/components/Editor/TinymceEditor.vue";
import {getDictOneByXmhjc, getFileList,getFileStr} from "@/api/XMHJC/common";
import {
  addColumnMenu, checkDeleteColumnMenuSub, deleteColumnMenu,
  editColumnMenu, findColumnArticleList,
  findColumnMenuList,
  getColumnMenu
} from "@/api/XMHJC/column";
import {isNullOrUndefined} from "@tinymce/tinymce-vue/lib/es2015/main/ts/Utils";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");

let rules = ref({
  name: [{ required: true, message: "请输入企业文化标题", trigger: "blur" }],
  status: [{ required: true, message: "请选择启用状态", trigger: "change" }],
  subStatus: [{ required: true, message: "请选择启用状态", trigger: "change" }],
  type: [{ required: true, message: "请选择跳转类型", trigger: "change" }],
  listType: [{ required: true, message: "请选择列表类型", trigger: "change" }],
  isRelated: [{ required: true, message: "请选择是否开启", trigger: "change" }],
  url: [{ required: true, message: "请输入第三方链接", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  subName: [{ required: true, message: "请输入子栏目", trigger: "blur" }],
  subSort: [{ required: true, message: "请输入排序", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const columnType = ref([]);
const columListType = ref([]);
const enableStatus = ref([]);
const selectConfig = [];
const config = computed(() => {
  return [
    {
      attrs: {
        label: "栏目名称",
        prop: "name",
      },
    },

    {
      attrs: {
        label: "栏目类型",
        prop: "type",
      },
      render(type) {
        return proxy.dictValueLabel(type, columnType.value);
      },
    },
    {
      attrs: {

        label: "列表类型",
        prop: "listType",
        slot: 'listType',
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "status",
        width: '80'
      },
      render(type) {
        return proxy.dictValueLabel(type, enableStatus.value);
      },
    },

    {
      attrs: {
        label: "排序",
        prop: "sort",
        width: '80'
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                deleteColumnMenu({
                  id: row.id,
                })
                    .then((res) => {
                      ElMessage({
                        message: "删除成功",
                        type: "success",
                      });
                      getList();
                    });
              });
            },
          },
        ];
      },
    },
  ];
});
let formData = reactive({
  data: {
    columnMenuSubList:[],
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "name",
      label: "栏目名称",
      required: true,
    },
    {
      type: "select",
      prop: "type",
      label: "栏目类型",
      clearable: true,
      data: columnType.value,
      required: true,
    },
    {
      type: "select",
      prop: "isRelated",
      label: "是否开启相关文章",
      data: enableStatus.value,
      required: true,
      clearable: true,
      isShow: formData.data.type == "1"
    },
    {
      type: "slot",
      slotName: "subColumn",
      prop: "subColumn",
      label: "子栏目",
      isShow: formData.data.type == "1"
    },
    {
      type: "select",
      prop: "listType",
      label: "列表类型",
      data: columListType.value,
      required: true,
      clearable: true,
      isShow: formData.data.type == "1"
    },
    {
      type: "slot",
      slotName: "detailsContent",
      prop: "detailsContent",
      label: "详情内容",
      isShow: formData.data.type == "2"
    },
    {
      type: "input",
      prop: "url",
      label: "第三方链接",
      required: true,
      isShow: formData.data.type == "3"
    },



    {
      label: "启用状态",
      prop: "status",
      type: "select",
      clearable: true,
      data: enableStatus.value,
      required: true,
    },
    {
      type: "input",
      prop: "sort",
      label: "排序",
      itemType: "number",
      precision: 0,
      max: 999,
      required: true,
    },
  ];
});

const getDictlist = async () => {

  const res = await getDictOneByXmhjc(["column_type","enable_status","column_list_type"]);
  columnType.value = res["column_type"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
  enableStatus.value = res["enable_status"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
  columListType.value = res["column_list_type"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;

  const res = await findColumnMenuList(sourceList.value.pagination);
  sourceList.value.data = res.data.rows;
  sourceList.value.pagination.total = res.data.total;
  setTimeout(() => {
    loading.value = false;
  }, 200);

};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    content:'',
    columnMenuSubList:[],
  };

};
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};
const submitForm = () => {
  byform.value.handleSubmit(() => {
    if(formData.data.type == '1'){
      if (!(formData.data.columnMenuSubList && formData.data.columnMenuSubList.length > 0)) {
        // formData.data.columnMenuSubList = [];

        ElMessage({message: "请填写子栏目",type: "error",});
        return
      }
    }

    if (formData.data.type == '2' &&
        !formData.data.content) {
      ElMessage({message: "请填写详情内容",type: "error",});
      return
    }

    submitLoading.value = true;
    if (modalType.value === 'add'){
      addColumnMenu(formData.data).then(response => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      }).catch(()=>{
        submitLoading.value = false;
      });
    }else {
      editColumnMenu(formData.data).then(response => {
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      }).catch(()=>{
        submitLoading.value = false;
      });


    }
  });
};

const getDtl = async (row) => {
  modalType.value = "edit";
  const response = await getColumnMenu({ id: row.id })
  formData.data = response.data;
  dialogVisible.value = true;
};


const updateHandover = (val) => {
  formData.data.content = val;
};


const clickAddSubColumn = () => {
  if (formData.data.columnMenuSubList && formData.data.columnMenuSubList.length > 0) {

    const  sort = formData.data.columnMenuSubList[formData.data.columnMenuSubList.length-1].sort

    formData.data.columnMenuSubList.push({
      name: "",
      sort: sort+10,
    });
  } else {
    formData.data.columnMenuSubList = [
      {
        name: "",
        sort: 10,
      },
    ];
  }

};

const getCellColumn = (row) =>{

  if (row.type != '1'){
    return  "——"
  }else {
    const  label = columListType.value.filter( (x) => {
      if (x.value == row.listType){
        return true
      }
      return false
    })
    return  label.length > 0 ? label[0].label:'';
  }
}

const clickDelete = async (index) => {
  console.log(isNullOrUndefined(formData.data.columnMenuSubList[index].id))
  if (isNullOrUndefined(formData.data.columnMenuSubList[index].id)){
    formData.data.columnMenuSubList.splice(index, 1);
  }else {
      //验证是否能删除该子栏目
     const res = await  checkDeleteColumnMenuSub({id : formData.data.columnMenuSubList[index].id });
     if (res.data){
       formData.data.columnMenuSubList.splice(index, 1);
       return
     }else {
       ElMessage({message: "该栏目存在文章，删除失败!如不想显示请禁用",type: "error",});
       return
     }
  }

};

const getArticleList = async () => {
  const res = await findColumnArticleList({
    pageNum: 1,
    pageSize: 99999,
    status: 1,
  });
  articleList.value = res.data.rows.map((x) => ({
    label: x.title,
    value: x.id,
  }));
};

getDictlist()
getList()

</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
  .delete-btn{
    margin-top: 10px;
    margin-left: 25px;
  }
}
.avatar-uploader .avatar {
  width: 110px;
  height: 110px;
  display: block;
  background-color: black;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
