<script lang="ts" setup>
import { ref, reactive, onMounted, inject, nextTick } from "vue";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { post, get } from "@/utils/request";
import { GET_ALL_STORES_TREE, GET_ALL_BUS_TABLE } from "../api"

import flowChart from './flowChart.vue'
import selectDeptUser from "./selectDeptUser.vue";
import { number } from "echarts";

const router = useRouter()
const route = useRoute()

const globalPopup = inject<GlobalPopup>('globalPopup')
const formVal = ref<addEditReportFormVal>({
  reportFormName: '',
  privilege: false,
  parentStoreId: '',
  description: '',
  deptAccessList: [],
  userAccessList: [],
  businessObject: []
})

const allVisable = reactive({
  mindMapVoisable: false,
  treeSelectUserVisable: false
})

const businessTableList = ref<optionType[]>([])
const treeSelectData = ref([])
const selectDeptUserRef = ref<InstanceType<typeof selectDeptUser> | null>(null);
const flowChartRef = ref<InstanceType<typeof flowChart> | null>()
const visibleRangeData = ref<any>([])

function openReport(val: string | number | boolean) {
  if (val) {
    visibleRangeData.value = []
  }
}
function visibleRangeDetermination() {
  const val = (selectDeptUserRef.value && selectDeptUserRef.value.getSelectData()) || []
  if (val.length == 0) {
    globalPopup?.showWarning('请先选择可见范围')
    return
  }
  val.sort((a, b) => {
    const isUserA = a.isUser === undefined ? -1 : a.isUser;
    const isUserB = b.isUser === undefined ? -1 : b.isUser;
    if (isUserA === isUserB) {
      return 0;
    }
    return isUserA < isUserB ? -1 : 1;
  });
  visibleRangeData.value = val
  allVisable.treeSelectUserVisable = false
}

function visibilityClose(index: number) {
  visibleRangeData.value.splice(index, 1)
}

function businessObjectSelectChange(val: any) {
  const row = businessTableList.value.find((item: any) => item.id === val)
  allVisable.mindMapVoisable = true
  nextTick(() => {
    flowChartRef.value?.initData(row)
  })
}

function showTreeDeptUserVis() {
  const list = (visibleRangeData.value || []).map((item: any) => item.id)
  allVisable.treeSelectUserVisable = true
  setTimeout(() => {
    selectDeptUserRef.value?.setTreeData(list)
  }, 200)
}

function getTreeClassification() {
  post(GET_ALL_STORES_TREE, {}).then((res) => {
    treeSelectData.value = res.data || []
  })
}

function getAllBusTable() {
  post(GET_ALL_BUS_TABLE, {}).then(res => {
    businessTableList.value = (res.data || []).map((item: any) => {
      return {
        label: item.name,
        value: item.id,
        ...item
      }
    })
  })
}

function dragAndDropEditing() {
  const mapData = flowChartRef.value?.exportGetData()
  const { reportFormName = '', privilege } = formVal.value
  if(!reportFormName) {
    globalPopup?.showWarning('请输入名称')
    return
  }
  if (!visibleRangeData.value.length && !privilege) {
    globalPopup?.showWarning('请选择可见范围')
    return
  }
  if (!mapData?.selectNodes.length) {
    globalPopup?.showWarning('请先选择业务对象')
    return
  }
  if (mapData?.selectNodes.length > 10) {
    globalPopup?.showWarning('最多只能选择10个业务对象')
    return
  }

  sessionStorage.setItem('reportJson', JSON.stringify({
    addFormVal: {
      ...formVal.value,
      visibleRangeData: visibleRangeData.value
    },
    mindMapJSON: mapData
  }))
  router.push({
    path: '/biReport/dragEdit',
  })
}

// 回显数据
function initializedData() {
  const reportJson = JSON.parse(sessionStorage.getItem('reportJson') || '{}')
  if(!Object.keys(reportJson).length) {
    return
  }
  console.log('reportJson', reportJson)
  const { addFormVal = {}, mindMapJSON = {} } = reportJson
  visibleRangeData.value = addFormVal.visibleRangeData || []
  formVal.value = addFormVal || {}
  setTimeout(() => {
    flowChartRef.value?.displayBackData(mindMapJSON)
  }, 500)
}

onMounted(() => {
  if(route?.query?.allParentStoreId) {
    formVal.value.parentStoreId = Number(route.query.allParentStoreId)
  }
  getTreeClassification()
  getAllBusTable()
  initializedData()
})
</script>

<template>
  <div class="w-full h-full flex flex-col bg-white rounded-md">
    <div class="p-5 text-[18px] border-b-2">
      {{ formVal.id ? '编辑报表' : '新建报表' }}
    </div>
    <div class="flex-1 py-5 px-16 flex-col flex h-[90%]">
      <div class="flex-1 h-full overflow-auto mb-8 scroll-bar">
        <el-form style="max-width: 600px" :model="formVal" label-width="80px">
          <el-form-item class="relative">
            <template #label>
              <div class="relative">
                名称
                <div class="absolute left-[-10px] top-[2px] text-[red]">*</div>
              </div>
            </template>
            <el-input v-model="formVal.reportFormName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="分类">
            <el-tree-select v-model="formVal.parentStoreId" :data="treeSelectData" check-strictly
            :render-after-expand="false" style="width: 100%" :props="{
                label: 'storeName', value: 'id', children: 'childStoreList'
              }" clearable />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="formVal.description" :rows="2" type="textarea" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="可见范围">
            <template #label>
              <div class="relative">
                可见范围
                <div class="absolute left-[-10px] top-[2px] text-[red]">*</div>
              </div>
            </template>
            <div class="flex items-center w-full">
              <el-input placeholder="+选择可见部门和人员" readonly :disabled="formVal.privilege"
                @click="showTreeDeptUserVis()" />
              <el-checkbox v-model="formVal.privilege" label="公开" size="large" class="ml-4" @change="openReport" />
            </div>
          </el-form-item>
          <el-form-item label=" " v-if="visibleRangeData.length">
            <div class="flex flex-wrap w-full">
              <template v-for="(item, index) in visibleRangeData">
                <el-tag :type="`${item.isUser ? 'warning' : 'primary'}`" closable class="mr-2 mb-2"
                  @close="visibilityClose(index)">
                  <TextTranslation :translationTypes="`${item.isUser ? 'userName' : 'departmentName'}`"
                    :translationValue="item.label"></TextTranslation>
                </el-tag>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="业务对象">
            <template #label>
              <div class="relative">
                业务对象
                <div class="absolute left-[-10px] top-[2px] text-[red]">*</div>
              </div>
            </template>
            <div class="flex w-full items-center">
              <el-select v-model="formVal.businessObject" placeholder="请选择" @change="businessObjectSelectChange">
                <el-option v-for="item in businessTableList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <div class="ml-4">
                <el-tooltip class="box-item" effect="dark" content="最多只能选择10个业务对象" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="h-[500px] border mr-6" v-if="formVal.businessObject">
          <flowChart ref="flowChartRef"></flowChart>
        </div>
      </div>
      <div class="justify-end flex">
        <el-button type="primary" @click="dragAndDropEditing()">下一步</el-button>
      </div>
    </div>

    <!-- 全屏对话框 -->
    <!-- <el-dialog v-model="allVisable.mindMapVoisable" fullscreen draggable class="fullScreen" :show-close="false">
      <div class="w-full h-full relative">
        <flowChart ref="flowChartRef"></flowChart>
        <div class="absolute flex justify-end right-2 bottom-2">
          <el-button @click="allVisable.mindMapVoisable = false">关闭</el-button>
          <el-button type="primary" @click="allVisable.mindMapVoisable = false">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog> -->

    <!-- 选择部门人员 -->
    <el-dialog v-model="allVisable.treeSelectUserVisable" width="600" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">选择可见范围</h4>
          <div>
            <el-button type="primary" @click="visibleRangeDetermination()">确定</el-button>
            <el-button @click="allVisable.treeSelectUserVisable = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="scroll-bar m-6">
        <selectDeptUser ref="selectDeptUserRef" />
      </div>
    </el-dialog>
  </div>
</template>

<style lang='scss' scoped>
/* 样式代码 */
.fullScreen :deep(.el-dialog__body) {
  width: 100%;
  height: 100%;
}
</style>