<template>
  <div ref="colItem" v-loading="loading" class="el-card is-hover-shadow">
    <el-row class="col-item__header">
      <el-col
        :span="20"
        class="title drag-handler"
        :class="[columnItem.showTitle != 0 ? 'header-title' : 'no-title']"
      >
        <span v-if="columnItem.showTitle != 0">{{ columnItem.name }}</span>
        <!-- <el-select
          v-if="columnItem.dropDown"
          v-model="columnItem.dropDownValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in columnItem.dropDownData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select> -->
      </el-col>

      <el-col :span="4" class="btn-group">
        <!-- <el-button
          v-if="columnItem.colUrl"
          type="text"
          title="更多"
          @click="openMore(columnItem.colUrl)"
        >
          <i class="el-icon-more"></i>
        </el-button> -->

        <el-button type="text" title="刷新" @click="refresh(columnItem)">
          <i class="el-icon-refresh"></i>
        </el-button>

        <el-button type="text" title="移除" @click="deleteColumn">
          <i class="el-icon-close"></i>
        </el-button>
      </el-col>
    </el-row>

    <div class="col-item__content">
      <v-runtime-template
        v-if="!isChart && !isCustomDialog"
        :parent="this"
        :template="decodeBase64ToHtml(columnItem)"
      />

      <ht-chart v-if="isChart" :id="chartId" :chart-key="chartId" />
      <custom-dialog
        v-if="isCustomDialog"
        ref="customDialog"
        :key="customDialog.alias"
        :is-show-pagination="isShowPagination"
        :alias="customDialog.alias"
        :custom-dialog="customDialog"
      />
    </div>

    <leader-dialog ref="leaderDialog" />
  </div>
</template>

<script>
  /* eslint-disable vue/no-unused-components */
  import OftenFlow from './OftenFlow'
  import homeUserInfo from './HomeUserInfo'
  import HomeNewsList from './HomeNewsList'
  import HomeCarousel from './HomeCarousel'
  import VRuntimeTemplate from 'v-runtime-template'
  import LeaderDialog from '@/views/matter/components/LeaderDialog'
  import CustomDialog from '@/views/home/components/CustomDialog'
  import req from '@/utils/request'
  import { parseExp } from '@/utils/parse.js'
  import { getMyOftenFlow } from '@/api/flow'
  import { getCustomDataByAlias } from '@/api/form.js'
  import CustomQuery from '@/services/CustomQuery.js'
  // 新注册的组件
  import Personalnformation from '@/views/home/components/HomeComponent/Personalnformation.vue'
  import CommonFunctions from '@/views/home/components/HomeComponent/CommonFunctions.vue'
  import TaskPanel from '@/views/home/components/HomeComponent/TaskPanel.vue'
  import ProjectSummary from '@/views/home/components/HomeComponent/ProjectSummary.vue'
  import CompanyNews from '@/views/home/components/HomeComponent/CompanyNews.vue'
  import SupervisionFeedback from '@/views/home/components/HomeComponent/SupervisionFeedback.vue'
  import ApprovalStatus from '@/views/home/components/HomeComponent/ApprovalStatus.vue'
  import BusinessConsulting from '@/views/home/components/HomeComponent/BusinessConsulting.vue'

  export default {
    name: 'HomeColumn',
    components: {
      Personalnformation, //个人信息栏目
      CommonFunctions, //常用功能
      TaskPanel, //任务面板
      CompanyNews, //公司新闻
      ProjectSummary, //项目汇总
      SupervisionFeedback, //督办反馈
      ApprovalStatus, //审批状态
      BusinessConsulting, //业务咨询
      OftenFlow,
      homeUserInfo,
      HomeNewsList,
      HomeCarousel,
      LeaderDialog,
      VRuntimeTemplate,
      CustomDialog,
    },
    props: {
      columnItem: {
        type: Object,
        required: true,
        default: () => null,
      },
    },
    data() {
      return {
        data: {},
        isChart: false,
        chartId: '',
        loading: false,
        portal: window.context.portal,
        html: '<span>本栏目无模板</span>',
        oftenFlowList: [],
        pageBean: {
          page: 1,
          pageSize: 10,
          total: 0,
          showTotal: false,
        },
        hotent: require('@/assets/index_images/hotent.png'),
        wechat: require('@/assets/index_images/wechat.png'),
        isCustomDialog: false,
        customDialog: { alias: '' },
      }
    },
    computed: {
      isShowPagination() {
        return this.customDialog.needPage ? false : true
      },
    },
    watch: {
      columnItem: {
        handler(val) {
          if (val) {
            this._getMyOftenFlow()
            this.handleColumnData(val)
          }
        },
        immediate: true,
      },
    },
    methods: {
      openMore(url) {},
      handleOpenUrl(url, newWin) {},
      handleTodoListClick(item) {},
      handleCurrentChange(currentPage) {},
      TableRowStyle({ row, rowIndex }) {},
      deleteColumn() {
        this.$confirm('确认删除该栏目吗？', '提示', {
          type: 'warning',
        })
          .then(() => {
            this.$emit('delete-column', this.columnItem)
          })
          .catch(() => {})
      },
      handleRowClick(path) {
        this.$router.push(path)
      },
      handleTodoClick(row, key = '') {
        this.$refs.leaderDialog.handleJumpsTodoPage(row, {
          isGetApprovalBtn: true,
          key,
        })
      },
      _getMyOftenFlow() {
        if (this.columnItem.alias === 'vueOftenFlow') {
          getMyOftenFlow().then((data) => {
            if (data && data.rows) {
              this.oftenFlowList = data.rows
            }
          })
        }
      },
      decodeBase64ToHtml(column) {
        if (column.templateHtml) {
          return Base64.decode(column.templateHtml)
        }
        return this.html
      },
      refresh(column) {
        this.loading = true
        this.$store
          .dispatch('menu/getColumnByAlias', column.alias)
          .then((data) => {
            this.$emit('column-refresh', data)
            setTimeout(() => {
              this.loading = false
            }, 300)
          })
          .catch(() => {
            this.loading = false
          })
      },
      handleColumnData(column) {
        const { colType, dataMode, dataParam } = column
        if ([1, 4].includes(colType)) {
          const dataObj = JSON.parse(dataParam)
          if (dataObj && dataObj.chartType === 2) {
            this.isChart = true
            this.chartId = dataObj.id
          } else {
            // TODO:其他情况
          }
        } else {
          // 0:一般栏目 2:滚动栏目
          switch (dataMode) {
            case 1:
              //自定义对话框
              this.getCustomDialogData()
              break
            case 3:
              // RESTFUL 查询
              this.getDataToParse(column)
              break
            case 4:
              // TODO:数据报表
              break
            case 5:
              // 关联查询
              if (column && column.alias) {
                CustomQuery.load(column.alias).then((resp) => {
                  this.data = resp
                })
              }
              break
          }
        }
      },
      getDataToParse(column) {
        const { dataFrom, colType, needPage, dataParam, requestType } = column
        if (!dataFrom || colType === 1) {
          return
        }

        // POST 请求参数
        const queryParams = {}
        if (needPage === 1) {
          queryParams.pageBean = this.pageBean
        }

        // GET 请求参数
        let urlParam = ''

        if (dataParam) {
          const ctx = {}
          if (this.$store.state.user) {
            const { userId, username } = this.$store.state.user
            ctx.curUserId = userId
            ctx.curUserAccount = username
          }
          column.dataParam = parseExp(column.dataParam, ctx)
        }

        const dataParamParse = JSON.parse(
          typeof dataParam != 'undefined' && dataParam !== ''
            ? dataParam.replace(/\\\\/g, '\\')
            : '[]'
        )
        if (dataParamParse) {
          for (let i = 0; i < dataParamParse.length; i++) {
            let { name, value } = dataParamParse[i]
            if (requestType === 'POST') {
              try {
                value = JSON.parse(value)
              } catch (e) {}

              const queryValue =
                name === 'pageBean'
                  ? { ...value, page: this.pageBean.page }
                  : name === 'querys'
                  ? [...value]
                  : value
              queryParams[name] = queryValue
            } else {
              urlParam =
                i > 0 ? `${urlParam}&${name}=${value}` : `?${name}=${value}`
            }
          }
        }

        // 根据请求参数获取数据
        const requestUrl = this.getRequestUrl(dataFrom)
        if (requestType === 'POST') {
          req.post(requestUrl, queryParams).then(
            (res) => {
              this.data = { ...res }
              if (needPage === 1) {
                this.pageBean.page = this.data.page || 1
                this.pageBean.pageSize = this.data.pageSize || 10
                this.pageBean.total = this.data.total || 0
              }
            },
            (err) => {
              this.html = `<span style='color:red;'>${err}</span>`
            }
          )
        } else {
          req.get(requestUrl + urlParam).then(
            (res) => {
              this.data = { ...res }
            },
            (err) => {
              this.html = `<span style='color:red;'>${err}</span>`
            }
          )
        }
      },
      getRequestUrl(dataFrom) {
        const { uc, form, portal, bpmModel, bpmRunTime } = window.context
        const reqUrl = dataFrom
          .replace('${uc}', uc)
          .replace('${form}', form)
          .replace('${portal}', portal)
          .replace('${bpmModel}', bpmModel)
          .replace('${bpmRunTime}', bpmRunTime)
        return reqUrl
      },
      getCustomDialogData() {
        let this_ = this
        let dataFrom = JSON.parse(this.columnItem.dataFrom || '{}')
        if (!dataFrom.alias) {
          this_.loading = false
          this_.isCommon = true
          return
        }
        getCustomDataByAlias(dataFrom.alias).then((customDialog) => {
          //格式化对话框的显示字段、返回字段、条件字段、排序字段
          customDialog.displayfield = JSON.parse(customDialog.displayfield)
          for (let i = 0; i < customDialog.displayfield.length; i++) {
            customDialog.displayfield[i].field =
              customDialog.displayfield[i].field.toUpperCase()
          }
          customDialog.resultfield = JSON.parse(customDialog.resultfield)
          customDialog.sortfield = JSON.parse(customDialog.sortfield)
          customDialog.conditionfield = JSON.parse(customDialog.conditionfield)
          //列表
          if (customDialog.style == 0) {
            this_.customDialog = customDialog
            this_.isCustomDialog = true
            this_.loading = false
            setTimeout(() => {
              this_.$refs.customDialog.initData() //显示自定义对话框列表预览弹框
            })
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .col-item__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid $base-border-color;
    padding: 0 18px;
    .title {
      flex: 1;
      color: var(--themeColor);
      font-size: $base-font-size-big;
      padding: 16px 0;
      cursor: move;
    }
    .header-title {
      &::before {
        position: relative;
        top: 3px;
        display: inline-block;
        content: '';
        width: 4px;
        height: 19px;
        margin-right: 10px;
        background: var(--themeColor);
      }
      span {
        font-weight: 600;
        color: #000000;
      }
    }
    .no-title {
      padding: 28px 0;
    }
    .btn-group {
      padding: 5px 0;
      display: flex;
      justify-content: flex-end;
    }
    i {
      font-size: $base-font-size-default;
    }
  }
  .col-item__content {
    padding: 16px 18px;
  }

  // 个人信息栏目
  ::v-deep .grxxlm {
    .grxxlm-color {
      color: #919191;
    }
  }

  // 常用系统
  ::v-deep .cyxt {
    .cyxt-color {
      color: #919191;
    }
  }

  // 我的待办
  ::v-deep .my-todo {
    background: transparent;
  }
</style>
