<template>
  <div class="white">
    <!-- <m-tabs :items="list" :index="activeIndex" :path="path" @click="handleClick"></m-tabs> -->
    <div class="pa-3">
      <m-filter :option="filter" @search="handleSearch">

      <template #btn>
        <div style="flex: 1" class="d-flex justify-end align-center">
          <v-icon>mdi-list-box-outline</v-icon>
          <v-switch
            class="mx-3"
            v-model="switchValue"
          ></v-switch>
          <v-icon>mdi-microsoft</v-icon>
        </div>
      </template>
      </m-filter>
      <div class="d-flex justify-end my-3">
        <v-btn class="buttons elevation-5" rounded color="primary" @click="handleAdd">
          <v-icon left>mdi-plus</v-icon>
          新增图表
        </v-btn>
      </div>
      <div v-show="switchValue" class="chartParentBox">
        <div v-for="(item, index) in dataList" :key="item.webSettingId" class="chartItemBox elevation-5">
          <div style="position: relative;" @mouseover="hoverIndex = index" @mouseout="hoverIndex = -1">
            <div style="overflow: hidden; cursor: pointer;" @click="handleEdit(item)">
              <v-img
                :src="item.content.coverImg ?? require(`@/assets/chartCustomized/line1.jpg`)"
                :position="item.content?.type === 'table' ? '': 'top center'"
                class="imgItem"
              />
            </div>
            <div class="chartItemInfo px-3">
              <div class="chartTitle">{{ item.content.name }}</div>
              <!-- 发布未发布标签 -->
              <v-tooltip bottom>
                <template v-slot:activator="{ on, attrs }">
                  <span v-bind="attrs" v-on="on" class="chartTag" :class="{ 'chartTagAct': item.content?.showInPersonalCharts }">
                    {{ item.content?.showInPersonalCharts ? '已发布' : '未发布' }}
                  </span>
                </template>
                <span>{{ item.content?.showInPersonalCharts ? '已发布到定制图表汇总区域' : '未发布到定制图表汇总区域' }}</span>
              </v-tooltip>
            </div>
            <!-- 顶部操作 -->
            <div v-show="isContentVisible(index)" class="handleIcon">
              <div v-if="item.content?.showInPersonalCharts">
                <v-tooltip bottom>
                  <template v-slot:activator="{ on, attrs }">
                    <v-icon
                      small color="#757575" class="ma-1"
                      v-bind="attrs" v-on="on"
                      @click.stop="unpublish(item)"
                    >mdi-book-off-outline</v-icon>
                  </template>
                  <span>取消发布</span>
                </v-tooltip>
              </div>
              <div v-else>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on, attrs }">
                    <v-icon
                      small color="#2196f3" class="ma-1"
                      v-bind="attrs" v-on="on"
                      @click.stop="release(item)"
                    >mdi-book-check-outline</v-icon>
                  </template>
                  <span>发布</span>
                </v-tooltip>
              </div>
              <v-tooltip bottom>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon
                    v-bind="attrs"
                    v-on="on"
                    small
                    class="ma-1"
                    color="primary"
                    @click.stop="handleEdit(item)"
                  >
                    mdi-square-edit-outline
                  </v-icon>
                </template>
                <span>编辑</span>
              </v-tooltip>
              <v-tooltip bottom>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon
                    v-bind="attrs"
                    v-on="on"
                    small
                    class="ma-1"
                    color="error"
                    @click.stop="handleDelete(item)"
                  >
                    mdi-trash-can-outline
                  </v-icon>
                </template>
                <span>删除</span>
              </v-tooltip>
            </div>
            <!-- 顶部操作 -->
          </div>
        </div>
      </div>
      <div v-show="switchValue && total > 0">
        <m-pagination :total="total" :page="pageInfo.current" @handleChange="pageHandleChange"></m-pagination>
      </div>
      <m-table
        v-show="!switchValue"
        :is-mb="false"
        :headers="headers"
        :items="dataList"
        :loading="loading"
        :total="total"
        :page="pageInfo"
        :show-select="false"
        :disable-sort="true"
        :is-tools="false"
        @edit="handleEdit"
        @pageHandleChange="pageHandleChange"
      >
        <template #name="{ item }">{{ item.content.name }}</template>
        <template #status="{ item }">
          <v-chip small :color="item.content?.showInPersonalCharts ? 'success' : 'default'">
            {{ item.content?.showInPersonalCharts ? '已启用' : '未启用' }}
          </v-chip>
        </template>
        <template #type="{ item }">{{ item.content.type }}</template>
        <template #actions="{ item }">
          <v-btn text color="primary" @click="handleEdit(item)">编辑</v-btn>
          <v-btn text color="error" @click="handleDelete(item)">删除</v-btn>
          <v-btn v-if="!item.content?.showInPersonalCharts" text color="success" @click="release(item)">启用</v-btn>
          <v-btn v-if="item.content?.showInPersonalCharts" text color="warning" @click="unpublish(item)">关闭</v-btn>
        </template>
      </m-table>
    </div>

    <m-dialog
      :visible.sync="showEditBox"
      fullscreen
      flex-box
      :title="title + '图表'"
      :footer="false"
      no-click-animation
      body-style="padding: 0; overflow: hidden;"
    >
      <edit v-if="showEditBox" :row-obj="rowObj" @submit="handleSubmit" class="pa-2"></edit>
    </m-dialog>
  </div>
</template>

<script>
import MFilter from '@/components/Filter'
import MPagination from '@/components/Pagination'
// import MTabs from '@/components/Tabs'
import MDialog from '@/components/Dialog'
// import FilterList from '@/components/Filter'
import MTable from '@/components/List/table'
import edit from './edit.vue'
import { getSettingList, saveSettingList, deleteSettingList } from '@/api/system'
import {
  // getAuthenticationSystreePage,
  // authenticationSystreeSave,
  // authenticationSystreeDel,
  digitizationDataChartSave,
  digitizationDataChartDel
} from '@/api/chartCustomized'
export default {
  name: 'my-chart-diagram',
  components: {
    MPagination,
    // MTabs,
    MTable,
    // FilterList,
    MFilter,
    edit,
    MDialog
  },
  data () {
    return {
      switchValue: false,
      filter: {
        list: [
          { type: 'textField', value: '', label: '分类', key: 'classify' },
          { type: 'datePicker', value: '', label: '时间', key: 'createTime' }
          // { type: 'autocomplete', value: null, label: '选择', key: 'type', items: [] }
        ]
      },
      hoverIndex: -1,
      list: [],
      // activeIndex: 0,
      dataList: [],
      // path: '',
      loading: false,
      headers: [
        { text: '图表名称', value: 'name' },
        { text: '分类', value: 'classify' },
        { text: '制作者', value: 'author' },
        { text: '制作时间', value: 'time' },
        { text: '状态', value: 'status' },
        { text: '类型', value: 'type' },
        // { text: '标识码', value: 'code' },
        // { text: '所属分类', value: 'chartClassificationId' },
        { text: '操作', value: 'actions' }
      ],
      items: [],
      total: 0,
      pageInfo: {
        current: 1,
        size: 10
      },
      searchObj: { searchName: '' },
      showEditBox: false,
      title: '新增',
      rowObj: {}
    }
  },
  created () {
    this.init()
    // this.list = this.$route.meta.roles
    //   .sort((a, b) => a.sort - b.sort)
    //   .filter(item => +item.active)
    //   .map(e => ({ title: e.label, path: e.name }))
    // const savedTab = new URLSearchParams(window.location.search).get('tab')
    // if (!savedTab) {
    //   this.activeIndex = 0
    //   // this.path = this.list[0].name
    //   return
    // }
    // this.path = savedTab
    // this.activeIndex = this.list.findIndex(e => e.path === savedTab)
  },
  methods: {
    async init () {
      try {
        this.loading = true
        // 自动配置图表参数 chartList
        const { data } = await getSettingList({
          page: this.pageInfo,
          entity: { webSettingCategory: 'chartList' },
          ...this.searchObj
        })
        if (!data.records) return
        this.dataList = data.records.map(item => item.entity)
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    // handleClick (item) {
    //   this.activeIndex = item.value
    //   this.path = item.path
    //   this.$router.push(`${this.$route.path}?tab=${item.path}`)
    // },
    pageHandleChange (index) {
      this.pageInfo.current = index
      this.init()
    },
    handleSearch (val) {
      this.searchObj = val
      this.pageInfo.current = 1
      this.init()
    },
    async handleSubmit (params) { // 保存
      try {
        await saveSettingList(params)
        this.$snackbar.success('保存成功')
        this.showEditBox = false
        await this.init()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleAdd () {
      this.showEditBox = true
      this.title = '新增'
      this.rowObj = {}
    },
    handleEdit (item) {
      this.title = '编辑'
      if (item.content.showInPersonalCharts) {
        this.$snackbar.warning('请先取消共享，再进行编辑')
        return
      }
      this.rowObj = item // 处理数据
      this.showEditBox = true
    },
    handleDelete (item) {
      const bool = item.content.showInPersonalCharts
      const tip = bool ? '是否删除该选项' : '将同步从团队共享移除，是否继续删除该数据？'
      this.$confirm('系统提示', tip).then(async () => {
        try {
          await deleteSettingList({ webSettingId: item.webSettingId.toString() })
          if (bool) await digitizationDataChartDel({ chartId: item.content.chartId })
          this.$snackbar.success('删除成功')
          this.init()
        } catch (error) {
          this.$snackbar.error(error)
        }
      })
    },
    // 撤销发布
    unpublish (item) {
      this.$confirm('系统提示', '是否取消共享？').then(async () => {
        try {
          await digitizationDataChartDel({ chartId: item.content.chartId })
          item.content.showInPersonalCharts = false
          await saveSettingList(item)
          this.init()
          this.$snackbar.success('操作成功，已取消共享')
        } catch (error) {
          this.$snackbar.error(error)
        }
      })
    },
    // 发布
    release (item) {
      this.$confirm('系统提示', '将添加到团队共享展示，是否继续？').then(async () => {
        try {
          const obj = {
            chartName: item.content.name,
            treeId: item.content.chartClassificationId, // 图表分类id
            chartParam: item.content
          }
          const chartId = item.content.chartId // chartCustomizedCreate中的数据id
          if (chartId) obj.chartId = chartId
          const { data } = await digitizationDataChartSave(obj)
          if (!chartId) item.content.chartId = data.chartId // 第一次发布
          item.content.showInPersonalCharts = true
          await saveSettingList(item) // 保存个性化定制图表汇总数据的id，用于再次发布或者撤销发布
          this.init()
          this.$snackbar.success('操作成功，已添加到团队共享！')
        } catch (error) {
          this.$snackbar.error(error)
        }
      })
    },
    isContentVisible (index) {
      return this.hoverIndex === index
    },
    initRoute (item) { // 用于第一次发布生成路由信息
      return {
        active: '1',
        enName: '',
        label: item.content.name,
        meta: {
          enName: '',
          title: item.content.name,
          itemObjContent: item.content
        },
        name: 'customCharts',
        sort: 999 // item.content.sort
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chartParentBox {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  // background-color: #f4f4f4;

  .chartItemBox {
    display: flex;
    flex-direction: column;
    justify-content: left;
    // cursor: pointer;
    width: calc((100% - 48px) / 5);
    min-width: calc((100% - 48px) / 5);
    max-width: calc((100% - 48px) / 5);
    margin: 0 12px 12px 0;

    &:nth-child(5n) {
      margin-right: 0;
    }

    .handleIcon {
      width: 100%;
      padding: 4px 8px;
      position: absolute; top: 0; left: 0; background-color: rgba(0, 0, 0, 0.4);
      // text-align: end;
      display: flex;
      justify-content: flex-end;
    }
    .imgItem {
      width: 100%;
      height: 200px;
      cursor: pointer;
      transition: .3s ease-in-out;
      &:hover {
        transform: scale(1.1);
      }
    }

    .chartItemInfo {
      width: 100%;
      flex: 1;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;

      .chartTitle {
        flex: 1;
        height: 100%;
        font-size: 12px;
        font-weight: 600;
        line-height: 40px;
        text-align: left;
        white-space: nowrap;
        text-overflow: ellipsis;
        word-wrap: break-word;
        overflow: hidden;
      }
      .chartTag {
        // height: 100%;
        font-size: 12px;
        // font-weight: 600;
        // line-height: 40px;
        margin-left: 8px;
        padding: 2px 4px;
        color: #1e74cbed;
        border: 1px solid #1e74cb;
        border-radius: 4px;
      }
      .chartTagAct {
        color: #93cc78ed;
        border: 1px solid #92cc78;
      }
    }
  }
}
</style>
