<template>
  <HomeHead class="top"> </HomeHead>

  <div class="w-full h-1px bg-#507FFD mt50px rd-b-20px"></div>
  <div class="bg-#fff rd-15px px30px pt30px w-full">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-button
        class="float-right px20px py10px z-200 cursor-pointer felx items-center"
        type="info"
        @click="goBacks"
      >
        <el-icon class="text-red"><ArrowLeftBold size="18" /></el-icon> 返回
      </el-button>
      <el-tab-pane label="banner管理" name="first">
        <el-button type="primary" @click="editClickA('add')" class="mb-20px"> 新增 </el-button>

        <el-button
          class="button mt--20px"
          @click="getUser('1')"
          :type="userData ? 'success' : 'primary'"
          :icon="userData ? 'Check' : ''"
          >{{ userData ? '已设置' : '查看范围设置' }}</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="title" label="标题" align="center" />
            <el-table-column prop="imgUrl" label="图片" align="center">
              <template #default="scope">
                <div
                  style="
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    grid-template-rows: masonry;
                    grid-gap: 2px;
                  "
                >
                  <img
                    v-if="scope.row.imgUrl"
                    v-for="i in scope.row.imgUrl"
                    :src="i.url"
                    alt=""
                    class="w-full"
                  />
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="filePath" label="文件列表" align="center">
              <template #default="scope">
                <span v-if="scope.row.filePath" v-for="i in scope.row.filePath"
                  >{{ i.originalFileName }}<br
                /></span>
              </template>
            </el-table-column>
            <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="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
          class="button mt--20px"
          @click="getUser('2')"
          :type="userData ? 'success' : 'primary'"
          :icon="userData ? 'Check' : ''"
          >{{ userData ? '已设置' : '查看范围设置' }}</el-button
        >

        <div class="w100% h750px overflow-auto">
          <el-table
            :data="tableDataB"
            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="imgUrl" label="图片"  align="center">
                            <template #default="scope">
                                <img :src="scope.row.imgUrl" alt=""  class="w240px">
                            </template>
                            
                        </el-table-column> -->
            <el-table-column prop="title" label="标题" align="center" />
            <el-table-column prop="createTime" label="上传时间" align="center" />
            <el-table-column prop="filePath" label="文件列表" align="center">
              <template #default="scope">
                <span v-if="scope.row.filePath" v-for="i in scope.row.filePath"
                  >{{ i.originalFileName }}<br
                /></span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" @click="editClickB('edit', scope.row)" class="mb-20px">
                  编辑</el-button
                >

                <el-button type="danger" @click="deleteClickB(scope.row)" class="mb-20px">
                  删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </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.title" />
        </el-form-item>
        <br />
        <el-form-item label="图片">
          <!-- <el-upload v-model:file-list="editA.imgFile" class="upload-demo" :headers="header"
                        action="/test-api/common/upload"  :on-exceed="handOnExceed" :limit="1">
                        <el-button type="primary">选择图片</el-button>

                    </el-upload> -->
          <el-upload
            v-model:file-list="editA.imgFile"
            :headers="header"
            action="/test-api/common/upload"
            list-type="picture-card"
            :on-exceed="handOnExceed"
            :on-preview="handlePictureCardPreview"
            :limit="5"
            :multiple="true"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <br />

        <el-form-item label="文件">
          <el-upload
            v-model:file-list="editA.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="addClickA(editA)" class="mb-20px"> 确认</el-button>
        </div>
      </el-form>
    </div>
  </NModal>

  <NModal v-model:show="dialogVisible" :z-index="999999">
    <img class="object-contain max-w-65%" :src="dialogImageUrl" alt="选择图片" />
  </NModal>

  <NModal v-model:show="shomkB">
    <div class="bg-#FFF p30px">
      <el-form :model="editB" label-width="120px" :inline="true">
        <el-form-item label="标题">
          <el-input v-model="editB.title" />
        </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 />
        <el-form-item label="是否置顶">
          <el-switch
            v-model="editB.isTop"
            active-text="置顶"
            inactive-text="不置顶"
            :inactive-value="0"
            :active-value="1"
          ></el-switch>
        </el-form-item>
        <br />
        <el-form-item label="是否定时发送">
          <el-switch
            v-model="editB.isPublish"
            active-text="是"
            inactive-text="否"
            :inactive-value="0"
            :active-value="1"
            @change="(val) => (editB.publishTime = val ? pickerOptions.day : '')"
          ></el-switch>
        </el-form-item>
        <br />
        <el-form-item label="发布时间" v-if="editB.isPublish == 1">
          <el-date-picker
            v-model="editB.publishTime"
            align="right"
            type="date"
            placeholder="选择日期"
            :disabledDate="pickerOptions.disabledDate"
            :shortcuts="pickerOptions.shortcuts"
            :value-format="pickerOptions.valueFormat"
          >
          </el-date-picker>
        </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 HomeHead from '@/views/home/components/HomeHead.vue'
import { useUserStore } from '@/stores/modules/user'
import {
  updateFootprint,
  getFootprintList,
  saveFootprintUser,
  delFootprint,
  fetchGetViewScope
} from '@/api/daikin/base'
import { NModal, useMessage, NSelect } from 'naive-ui'
import UserList from '@/views/home/intelligence/process/UserPages.vue'
import { pickerOptions } from '@/utils/date'

const store = useUserStore()
const message = useMessage()

const tableData = ref()
const tableDataB = ref()

const shomkA = ref(false)
const shomkB = ref(false)
const editA = ref()
const editB = ref()
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 100,
  total: 10
})
const pageInfos = reactive({
  pageNum: 1,
  pageSize: 100,
  total: 10
})
async function getTree() {
  const { rows, total } = await getFootprintList({
    pageNum: pageInfo.pageNum,
    pageSize: pageInfo.pageSize,
    moduleId: '1'
  })
  const { rows: row, total: tota } = await getFootprintList({
    pageNum: pageInfos.pageNum,
    pageSize: pageInfos.pageSize,
    moduleId: '2'
  })
  pageInfo.total = total
  pageInfos.total = tota
  tableData.value = rows
  tableDataB.value = row
}

const activeName = ref('first')
const deptId = ref()
// onMounted(() => {
//     getTree()

// })
const editClickA = (edit: any, obj: any) => {
  console.table(obj)
  if (edit === 'add' && obj && obj.id) {
    editA.value = {
      title: '',
      moduleId: '1',
      filePath: [],
      imgUrl: [],
      type: edit,
      fileList: []
    }
    if (obj.filePath) {
      editA.value.fileList = [
        {
          name: obj.title,
          originalFilename: obj.filePath.originalFileName,
          url: obj.filePath.url
        }
      ]
    }
    dialogImageUrl.value = obj.imgUrl
    // dialogVisible.value = true
  } else if (obj && obj.id) {
    editA.value = obj
    if (obj.filePath) {
      // editA.value.fileList = [{
      //     name: obj.title,
      //     originalFilename: obj.originalFileName,
      //     url: obj.filePath.url,
      // }]
      editA.value.fileList = obj.filePath.map((item: any) =>
        Object.assign(item, {
          name: item.originalFileName,
          originalFilename: item.originalFileName,
          url: item.url
        })
      )
    }
    if (obj.imgUrl) {
      // editA.value.imgFile=[{
      //     name: obj.title,
      //     originalFilename: obj.title,
      //     url: obj.imgUrl,
      // }]
      editA.value.imgFile = obj.imgUrl.map((item: any) =>
        Object.assign(item, {
          name: item.originalFileName,
          originalFilename: item.originalFileName,
          url: item.url
        })
      )
    }
    dialogImageUrl.value = obj.imgUrl
    // dialogVisible.value = true
  } else {
    editA.value = {
      title: '',
      moduleId: '1',
      filePath: [],
      imgUrl: [],
      type: edit,
      fileList: []
    }
  }

  console.log(editA.value)
  shomkA.value = true
}
const deleteClickA = async (row: any) => {
  if (row && row.id) {
    const { code, msg } = await delFootprint({ id: row.id })
    if (code === 200) {
      message.success('删除成功')
    } else message.warning(msg)
  }
  getTree()
}
async function addClickA(row: any) {
  console.log(row)
  if (!row) return
  const { id, moduleId, title, fileList, imgFile } = row
  let filePath: any[] = [],
    imgUrl: any[] = []
  if (!imgFile) {
    message.error('图片不能为空')
    return
  } else {
    row.imgFile.forEach((index) => {
      if (index.response) {
        console.log(121212)
        // imgUrl = index.response.url
        imgUrl.push(index.response.url)
      } else {
        // imgUrl = index.url
        imgUrl.push(index.url)
      }
    })
  }
  if (fileList && fileList.length > 0) {
    console.log(1, 212121, fileList && fileList.length > 0, fileList)
    fileList.forEach((index) => {
      if (index.response) {
        console.log(212121)
        filePath.push(index.response.url)
        // filePath = index.response.url
      } else {
        filePath.push(index.url)
        // filePath = index.url
      }
    })
  }
  console.log(row)
  if (row.type === 'add') {
    const { code, msg } = await updateFootprint({
      id,
      moduleId,
      title,
      filePath,
      imgUrl
    })
    if (code === 200) {
      message.success('新增成功')
    } else message.warning(msg)
  } else {
    const { code, msg } = await updateFootprint({
      id,
      moduleId,
      title,
      filePath,
      imgUrl
    })
    if (code === 200) {
      message.success('修改成功')
    } else message.warning(msg)
  }
  shomkA.value = false
  getTree()
}
/****** */
const editClickB = (edit: any, obj: any) => {
  console.table(obj)
  if (edit === 'add' && obj && obj.id) {
    editB.value = {
      title: '',
      moduleId: '2',
      filePath: '',
      imgUrl: '',
      type: edit,
      fileList: []
    }
    if (obj.filePath) {
      // editB.value.fileList = [{
      //     name: obj.title,
      //     originalFilename: obj.filePath.originalFileName,
      //     url: obj.filePath.url,
      // }]
      editB.value.fileList = obj.filePath.map((item: any) =>
        Object.assign(item, {
          name: item.originalFileName,
          originalFilename: item.originalFileName,
          url: item.url
        })
      )
    }
  } else if (obj && obj.id) {
    editB.value = obj
    if (obj.filePath) {
      // editB.value.fileList = [{
      //     name: obj.title,
      //     originalFilename: obj.originalFileName,
      //     url: obj.filePath.url,
      // }]
      editB.value.fileList = obj.filePath.map((item: any) =>
        Object.assign(item, {
          name: item.originalFileName,
          originalFilename: item.originalFileName,
          url: item.url
        })
      )
    }
  } else {
    editB.value = {
      title: '',
      moduleId: '2',
      filePath: '',
      imgUrl: '',
      type: edit,
      fileList: []
    }
  }

  console.log(editB.value)
  shomkB.value = true
}
const deleteClickB = async (row: any) => {
  if (row && row.id) {
    const { code, msg } = await delFootprint({ id: row.id })
    if (code === 200) {
      message.success('删除成功')
    } else message.warning(msg)
  }
  getTree()
}
async function addClickB(row: any) {
  console.log(row)
  if (!row) return
  const { id, moduleId, title, fileList, imgFile, isPublish, publishTime, isTop } = row
  let filePath: any[] = []
  let url: any[] = []
  if (fileList && fileList.length > 0) {
    console.log(1, 212121, fileList && fileList.length > 0, fileList)
    fileList.forEach((index) => {
      if (index.response) {
        console.log(212121)
        filePath.push(index.response.url)
        // filePath = index.response.url
      } else {
        filePath.push(index.url)
        // filePath = index.url
      }
    })
  }
  console.log(row)
  if (row.type === 'add') {
    const { code, msg } = await updateFootprint({
      id,
      moduleId,
      title,
      filePath,
      isPublish,
      publishTime,
      isTop
    })
    if (code === 200) {
      message.success('新增成功')
    } else message.warning(msg)
  } else {
    const { code, msg } = await updateFootprint({
      id,
      moduleId,
      title,
      filePath,
      isPublish,
      publishTime,
      isTop
    })
    if (code === 200) {
      message.success('修改成功')
    } else message.warning(msg)
  }
  shomkB.value = false
  getTree()
}

const handleChange = (e: string | any[]) => {
  if (e && e.length > 1 && e.length <= 2) {
    // console.log(e, editB.value)
    editB.value.cateId = e[1]
  } else if (e && e.length > 2) {
    editB.value.cateId = e[2]
  } else {
    editB.value.cateId = e[0]
  }
  // console.log(e,editB.value.cateId,99999)
}
const handOnExceed: UploadProps['onExceed'] = (uploadFile: any, uploadFiles: any) => {
  message.warning('最多只能上传5张图片！')
}

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) {
  console.log(969696, row)
  showModal.value = !showModal.value
  flg.value = row
  //   if(row.id&&row.userList){
  //     setUserList.value = row.userList
  //   }
  const { data: userArr } = await fetchGetViewScope({ moduleId: row })
  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) {
    // flg.value.userIdList = userIdList
    saveFootprintUser({ userIdList, moduleId: flg.value })
    // getDataA();
    console.log(flg.value)
  }
  //   editA.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 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)
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview = (uploadFile: { url: string }) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
  //   console.log(dialogImageUrl.value)
}
</script>
<style lang="less">
::-webkit-scrollbar {
  width: 1px;
}
.top {
  position: absolute;
  right: 30px;
  top: -92px;
}
</style>
