<template>
    <DataBaseHead />
    <div class="w-full h-1px bg-#507FFD mt50px rd-b-20px"></div>
    <div class="bg-#fff rd-15px px30px pt30px w-full h920px ">
       
        <el-tabs v-model="activeName" class="demo-tabs">
            <div class="float-right px20px  py10px z-200 bg-#f5f5f5" @click="goBacks">   <el-icon class="text-red"><ArrowLeftBold size="18"/></el-icon> 返回</div>
            <el-tab-pane label="分类管理" name="first">
                <el-button type="primary" @click="editClickA('add')" class="mb-20px">
                   新增
                </el-button>
                <div class="w100% h750px overflow-auto">
                    <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border
                        default-expand-all :header-cell-style="{textAlign: 'center',
                            background: '#2A7BF7', color: '#fff',
                            height: '60px', 'font-size': '24px'
                        }" :cell-style="{  'overflow-y': 'auto' }" 
                        :tree-props="{ children: 'childList', hasChildren: 'hasChildren'}">
                        <el-table-column prop="name" label="标题名称"  align="left"/>
                        <el-table-column prop="sort" label="排序"  align="center"/>
                        <el-table-column prop="address" label="操作"  align="center">
                            <template #default="scope">
                                <el-button type="primary" @click="editClickA('edit', scope.row)" class="mb-20px">
                                    编辑</el-button>
                                <el-button type="success" v-if="scope.row.level === 1||scope.row.level === 2||scope.row.level === 3" @click="editClickA('add', scope.row)"
                                    class="mb-20px"> 新增{{scope.row.level===1?'二':scope.row.level===2?'三':'四'}}级</el-button>
                                <el-button type="danger" @click="deleteClickA(scope.row)" class="mb-20px"> 删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>
            <el-tab-pane label="内容管理" name="second">
                <el-button type="primary" @click="editClickB('add')" class="mb-20px"> 新增</el-button>
                <el-button type="primary" @click="getAll" class="mb-20px"> 查看所有</el-button>
                <div class="w100% h750px overflow-auto" >
                    <el-table class="tableClass" :data="infoData" style="width: 100%; margin-bottom: 20px" row-key="id" border
                        default-expand-all :header-cell-style="{
                            background: '#2A7BF7', color: '#fff',
                            height: '60px', textAlign: 'center', 'font-size': '24px'
                        }" :cell-style="{ 'text-align': 'center', 'overflow-y': 'auto' }" 
                        :tree-props="{ children: 'childList', hasChildren: 'hasChildren'}">
                        <el-table-column prop="cateName" label="所属分类" show-overflow-tooltip>
                            <!-- <template #default="scope">
                                <span v-if="scope.row.cateId==="></span>
                            </template> -->
                        </el-table-column>
                        <el-table-column prop="title" label="标题名称" show-overflow-tooltip/>
                        <!-- <el-table-column prop="deptName" label="排序" /> -->
                        <el-table-column label="文件列表" prop="filePath" show-overflow-tooltip/>
                        <el-table-column label="排序" prop="sort" show-overflow-tooltip/>
                        <el-table-column label="查看范围" prop="userIdList" :show-overflow-tooltip="true"> 
                            <template  #default="scope">
                                <!-- <el-button type="primary"  class="button" @click="getUser(scope.row)">查看范围</el-button> -->
                                
                                <!-- <span class="descStyle" v-if="scope.row.userList" v-for="it in scope.row.userList"> &nbsp;&nbsp; {{it.nickName}}</span> -->
                                <!-- <span>{{ scope.row.userList }}</span> -->
                                <span v-if="scope.row.userList" v-for="(it,e) in scope.row.userList"> 
                                    <el-tooltip :content="it.nickName" placement="top">
                                        <p class="descStyle">{{ it.nickName }} <span v-if="e=== 1 && scope.row.userList.length > 2" >...共{{ scope.row.userList.length }}人</span> </p>
                                    </el-tooltip>
                                 </span>
                               
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="操作" show-overflow-tooltip>
                            
                            <template #default="scope">
                             
                                <div>
                                <el-button type="primary" @click="editClickB('edit', scope.row)" class="mb-20px w45px">
                                    编辑</el-button>
                                <el-button type="danger" @click="deleteClickB(scope.row)" class="mb-20px w45px"> 删除</el-button>
                                <div style="float: right;"  v-if="scope.$index !== 0 && scope.$index !==infoData.length-1">
                                    <el-button style="color: #000;width: 45px;height: 33px;"  @click="onUpload(scope.row)">
                                    <el-icon><Upload /></el-icon>
                                    </el-button>
                                    <el-button style="color: #000;width: 45px;height: 33px;"  @click="ondownloads(scope.row)">
                                    <el-icon><Download /></el-icon>
                                    </el-button>
                                
                                </div>
                                </div>
                            </template>
                        
                        </el-table-column>
                    </el-table>
                </div>

                <div class="float-right absolute bottom-0px right-30px z-2000 bg-#fff">
                <el-pagination v-model:current-page="pageInfo.currentPage" v-model:page-size="pageInfo.pageSize" 
                  layout="prev, pager, next, jumper" :total="pageInfo.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
              </div>
            </el-tab-pane>
        </el-tabs>







    </div>
    <NModal v-model:show="shomkA">
        <div class="bg-#FFF p30px">
            <el-form :model="editA" label-width="120px" :inline="true">
                <el-form-item label="标题">
                    <el-input v-model="editA.name" />
                </el-form-item>
                <br />
                <el-form-item label="排序">
                    <el-input type="number" v-model="editA.sort" />
                </el-form-item>
                <br />
                <div class="text-center">
                    <el-button type="primary" @click="addClickA(editA)" class="mb-20px"> 确认</el-button>
                </div>

            </el-form>
        </div>
    </NModal>
    <NModal v-model:show="shomkB">
        <div class="bg-#FFF p30px">
            <el-form :model="editB" label-width="120px" :inline="true">
                <!-- <el-form-item label="标题" v-if="editB.type!='add'"> -->
                <el-form-item label="标题">
                    <el-input v-model="editB.title" />
                </el-form-item>
                <br />
                <el-form-item label="排序">
                    <el-input v-model="editB.sort" type="number" />
                </el-form-item>
                <br />
                <el-form-item label="所属类别">
                    <el-cascader v-model="editB.cateId" :options="tableData" @change="handleChange"
                        :props="{ children: 'childList', label: 'name', value: 'id' }" />
                </el-form-item>
                <br />
                <el-form-item label="查看范围">
                    <el-button   class="button" @click="getUser"  :type="userData?'success':''"  :icon="userData?'Check':''">{{userData?'已设置':'设置'}}</el-button>
                </el-form-item>
              
                <br/>
                <el-form-item label="文件">
                    <el-upload v-model:file-list="editB.fileList" class="upload-demo" :headers="header"
                        action="/test-api/common/upload"  :on-exceed="handOnExceed" multiple="true">
                        <el-button type="primary">选择文件</el-button>

                    </el-upload>
                </el-form-item>
                <br />
                <div class="text-center">
                    <el-button type="primary" @click="addClickB(editB)" class="mb-20px"> 确认</el-button>
                </div>

            </el-form>
        </div>
    </NModal>
    <n-modal v-model:show="showModal">
        <UserList :userDataList="setUserList" @clickChild="handleChild"  @CloseThis="CloseThiss"/>
    </n-modal>
</template>

<script setup lang="ts">
import DataBaseHead from "@/views/home/components/DataBaseHead.vue";
import { useUserStore } from '@/stores/modules/user'
import { cateAdd, cateUpdate, treeDbList, cateInfo, cateDel, cateFileUpdate, cateFileDel, cateFileList, download, dragFile } from '@/api/daikin/base'
import { NModal, useMessage, NSelect } from "naive-ui";
import UserList from '@/views/home/intelligence/process/UserPages.vue'
import {databaseld} from "@/stores/modules/database" 

const database = databaseld()
const message = useMessage()

const tableData = ref()
const infoData = ref()

const shomkA = ref()
const editA = ref()
const shomkB = ref()
const editB = ref()
const activeName = ref('first')
const pageInfo = reactive({
  currentPage:1,
  pageSize:10,
  total:10
})
async function getTree() {
    const { data } = await treeDbList({})
    tableData.value = data
}
let cateIds = ref()
watchEffect(()=>{
    cateIds.value = database.database.id
    console.log(database.database.id)
    if(database.database.id){
        getInfo(database.database.id)
    }
  
})
async function getInfo(cateId: string | undefined) {
    const { rows,total } = await cateFileList({ cateId:cateIds.value, pageNum: pageInfo.currentPage, pageSize: pageInfo.pageSize })
    infoData.value = rows
    pageInfo.total = total
    if(rows&&rows.length>0){
        rows.map((item: { filePath: any; })=>Object.assign(item,{
            fileList: item.filePath
        }))
    }
}
const store = useUserStore()
const deptId = ref()
onMounted(() => {
    // getTree()
    // getInfo('')
    deptId.value = store.user.deptId
})
const editClickA = (edit: any, obj: any) => {
    console.table(obj)
    if (edit === 'add' && obj && obj.id) {
        editA.value = {
            name: '',
            sort: '',
            pid: obj.id,
            type: edit
        }
    }
    else if (obj && obj.id) {
        editA.value = obj
    }
    else {
        editA.value = {
            name: '',
            sort: '',
            pid: '0',
            type: edit
        }
    }


    console.log(editA.value)
    shomkA.value = true
}
const deleteClickA = async (row: any) => {
    if (row && row.id) {
        const { code, msg } = await cateDel({ id: row.id })
        if (code === 200) { message.success("删除成功") }
        else message.warning(msg)
    }
    getTree()
}
async function addClickA(row: any) {
    if (!row) return
    if (row.type === 'add') {
        const { code, msg } = await cateAdd(row)
        if (code === 200) { message.success("新增成功") }
        else message.warning(msg)
    }
    else {
        const { code, msg } = await cateUpdate(row)
        if (code === 200) { message.success("修改成功") }
        else message.warning(msg)
    }
    shomkA.value = false
    getTree()
}
const editClickB = (edit: any, obj: any) => {
    console.log(obj)
    if (edit === 'add' && obj && obj.id) {
        editB.value = {
            title: '',
            cateId: '',
            deptId: deptId.value,
            filePath:[],
            fileList: [],
            type:edit,
            userList:[],
            sort:0
        }
        if(obj.filePath){
            editB.value.fileList = [{
                name: obj.title,
                originalFilename: obj.title,
                url: obj.filePath,
            }]
        }
      
    setUserList.value =obj.userList
    }
    else if (obj && obj.id) {
        editB.value = obj
        if(obj.filePath){
            editB.value.fileList = [{
                name: obj.title,
                originalFilename: obj.title,
                url: obj.filePath,
            }]
        }
     
    setUserList.value =obj.userList
    }
    else {
        editB.value = {
            cateId: '',
            deptId: deptId.value,
            title: '',
            filePath: [],
            fileList: [],
            type:edit,
            userList:[],
            sort:0
        }
        setUserList.value = []
      
    }
    userData.value = false
    console.log(editB.value)
    shomkB.value = true
}
const deleteClickB = async (row: any) => {
    if (row && row.id) {
        const { code, msg } = await cateFileDel({ id: row.id })
        if (code === 200) { message.success("删除成功") }
        else message.warning(msg)
    }
    getInfo('')
}
async function addClickB(row: any) {
    console.log(row,deptId.value)
    if (!row) return
    let url: any[] =[]
    if(row.fileList&&row.fileList.length>0){
        row.fileList.forEach((index)=>{
          if(index.response){
            url.push(index.response.url)
          }
          else{
            url.push(index.url)
          }
           
        })
        
        row.filePath = url
        // console.log(url, row.filePath )
    }
    let list: any[] =[] 
    if(row.userList&&row.userList.length>0){
        console.log(row)
        row.userList.forEach((index) => {
            list.push(index.userId)
        })
        row.userIdList =list
    }
    if(!row.cateId){
        message.error("所属类别不能为空！")
        return
    }
    if (row.type === 'add') {
        const { code, msg } = await cateFileUpdate(row)
        if (code === 200) { message.success("新增成功") }
        else message.warning(msg)
    }
    else {

        const { code, msg } = await cateFileUpdate(row)
        if (code === 200) { message.success("修改成功") }
        else message.warning(msg)
    }
    shomkB.value = false
    getInfo('')
}
const handleChange = (e: string | any[]) => {
    // console.log(e.length)
    if (e && e.length == 1) {
        // console.log(e, editB.value)
        editB.value.cateId = e[0]
    }
    else if(e && e.length == 2){
        editB.value.cateId = e[1]
    }
    else if(e && e.length == 3){
        editB.value.cateId = e[2]
    }
    else if(e && e.length == 4){
        editB.value.cateId = e[3]
    }
    else {
        editB.value.cateId = e[0]
    }
    // console.log(e,editB.value.cateId,99999)
}
const handOnExceed: UploadProps['onExceed'] = (uploadFile: any, uploadFiles: any) => {
    message.warning("最多只能上传一个文件！")
}

const header = { 'token': store.user.token }
const goBacks=(e)=>{
    // console.log(444)
    history.back()
}
const showModal = ref(false)
const flg = ref()
const setUserList =ref()
async function getUser(row: { id: any; userList: any; }) {
  console.log(row)
  showModal.value = !showModal.value
  flg.value = row
  if(row.id&&row.userList){
    setUserList.value = row.userList
  }
  // const {data: userArr} = await getBPCUser({moduleId})
  // setUserList.value = userArr
    
}
  // 获取子组件传过来的值
  const userData = ref(false)
  const handleChild = (data: any) => {
    console.log(data, 444);
      const { showModal: show, multipleSelection } = data
      showModal.value = unref(show)
      let userIdList: any[] =[]
      multipleSelection.value.forEach((i: { userId: any })=>{
          userIdList.push(i.userId)
      })  
      if(flg.value.id){
        flg.value.userIdList = userIdList
        // marketPreADD(flg.value)
        // getDataA();
        console.log(flg.value)
      }
      editB.value.userIdList = userIdList
      if(userIdList.length>0){
        userData.value = true
        console.log(userIdList,8888)
      }
      else  userData.value = false
   
  }
  const CloseThiss = (data: boolean)=>{
      showModal.value = data
  }
const getAll=()=>{
    // cateIds.value = ''
    getInfo()
}

const lazyState = computed(() => [pageInfo.currentPage])
  watch(
    () => unref(lazyState),
    async (v) => {
      getTree()
    },
    { immediate: true, deep: true },
  )

const handleSizeChange=(e)=>{
  console.log(e)
}

const handleCurrentChange=(e)=>{
  console.log(e)
}
// 上移
async function onUpload(it){
    console.log(infoData);
  // 当前数据的索引
  let index = infoData._rawValue.findIndex((value :any) => value.id === it.id);
  index -= 1;
  const onUploaddate = await dragFile({
    cateId:it.cateId,
    curId:it.id,
    lastId:infoData._rawValue[index].id,
  });
  getInfo();
  
  
  console.log(infoData);
  console.log(it.cateId,"分类id");
  console.log(it.id, "当前位置的id");
  console.log(infoData._rawValue[index].id,"上移位置的id");
//   console.log(tableData._rawValue);
}
// 下移
async function ondownloads(it){
  // 当前数据的索引
  let index = infoData._rawValue.findIndex((value) => value.id === it.id);
  index += 1;
  // const {rows,total} = await cateFileList({cateId:prop.cateId,pageNum:currentPage,pageSize})
  const ondownloads = await dragFile({
    cateId:it.cateId,
    curId:it.id,
    lastId:infoData._rawValue[index].id,
  });
  getInfo();
  console.log(ondownloads);
}
</script>
<style lang="less">
::-webkit-scrollbar {
    width: 1px;
}

.tableClass .cell{   
    padding: 0!important;
    height: 50px;
    line-height: 25px !important;
    text-align: center;
  }
  .descStyle {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3; //行数
  -webkit-box-orient: vertical;
}
</style>