<template>
  <div class="design-container">
    <div class="main-body" v-loading="loading">
      <div class="main-tools">
        <el-button type="primary" link @click="handleClear" :disabled="disabled">
          <i class="icon-del"></i>{{ $t('clear') }}
        </el-button>
        <el-button type="primary" link @click="handlePreview">
          <i class="icon-eye"></i>{{ $t('preview') }}
        </el-button>
        <el-button type="primary" link @click="handleSave" :disabled="disabled">
          <i class="icon-save"></i>{{ $t('save') }}
        </el-button>
      </div>
      <AuditConfig v-if="state.activeTab === FormConfigType.AUDIT" :auditConfig="state.formConfig.auditConfig"
        :auditData="state.auditData" :disabled="disabled" @nodeClick="collspseForm" />
      <template v-else>
        <DragControl v-model:columnConfig="state.formConfig.columnConfig" v-model:columnData="state.columnData"
          style="display:inline-block" :disabled="disabled" />
        <div class="main-form" style="display:inline-block;vertical-align:top;width: calc(100% - 280px)">
          <div class="empty-tips" v-if="state.formConfig.columnConfig.length === 0">
            {{ $t('placeholder_design_form') }}
          </div>
          <FormDesign v-model:columnConfig="state.formConfig.columnConfig" v-model:columnData="state.columnData"
            v-model:data="data" draggable :disabled="disabled" :activated="state.formConfig.activated"
            @columnClick="collspseForm" />
        </div>
      </template>
    </div>
    <FormControlAttr ref="form" v-model:formConfig="state.formConfig" v-model:columnData="state.columnData"
      v-model:auditData="state.auditData" v-model:activePanel="state.activePanel" v-model:activeTab="state.activeTab"
      :disabled="disabled" />
    <el-dialog :title="$t('preview')" v-model="dialogVisible" destroy-on-close @closed="replace(previewData, {})">
      <FormDesign v-model:columnConfig="state.formConfig.columnConfig" v-model:data="previewData" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="WorkflowForm">
import DragControl from './dragControl.vue'
import FormControlAttr from './formControlAttr.vue'
import {onActivated, reactive, ref, getCurrentInstance, provide, nextTick } from 'vue'
import AuditConfig from './audit/config.vue'
import yid from 'yid'
import FormDesign from './formDesign.vue'
import { saveWorkFlowConfig, getDetail } from '@/api/workflowManagement'
import { FormInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { FormConfigPanel, FormConfigType } from '@/model/enums'
import { replace } from '@/utils/index';
import { useGlobalPinia } from '@/pinia/global'
// import { useRoutesStore } from '@/pinia/permission'
import moment from 'moment'
import { getDatePattern } from '@/components/GdElement/common';
import { ElMessage } from 'element-plus'
import useTagsViewStore from '@/store/modules/tagsView'

const { lang } = useGlobalPinia()
const router = useRouter()
const $t: any = getCurrentInstance()?.appContext.config.globalProperties.$t
// const routesStore = useRoutesStore()
// const currentRoute = useRoute()
const currentTag = router.currentRoute.value

const props = defineProps<{
  formId: any,
  disabled?: boolean
}>()

const defaultFlow = () => ({
  nodeId: yid(),
  nodeName: $t('flow_applicants'),
  type: 0,
  childNode: null,
})

// 当前表单配置
const state: any = reactive({
  formConfig: {
    optionType: '1',
    optionValue: '',
    needAudit: true,
    columnConfig: [],
    auditConfig: defaultFlow(),
  },
  // 右侧属性栏
  activePanel: FormConfigPanel.FORM_INFO,
  activeTab: FormConfigType.COLUMN,
  columnData: {},
  auditData: {}
})
provide('state', state)
provide('disabled', props.disabled)
const data = reactive({})
const previewData: any = reactive({})
const collspseForm = () => state.activePanel = ''

const handleClear = () => {
  switch (state.activeTab) {
    case FormConfigType.COLUMN:
      state.formConfig.columnConfig = [];
      replace(state.columnData, {})
      break;
    case FormConfigType.AUDIT:
      state.formConfig.auditConfig = defaultFlow();
      replace(state.auditData, {})
      break;
  }
  state.columnData.prop = undefined
}

const dialogVisible = ref(false)
const handlePreview = () => {
  state.formConfig.columnConfig.forEach((item: any) => {
    if (item.control === 'date-picker' && item.systemDate) {
      const now = moment().format(getDatePattern(null))
      item.defaultPropValue = item.type.includes('range') ? `${now},$${now}` : now
    }
    if (item.control === 'switch') {
      item.defaultPropValue = item.defaultPropValue || false
    }
    if (item.defaultPropValue !== undefined) {
      previewData[item.prop] = item.defaultPropValue
    }
  })
  dialogVisible.value = true
}

const form = ref<FormInstance>()
const handleSave = async () => {
  if (state.formConfig.columnConfig.length === 0) {
    ElMessage.warning($t('301020_0006'))
    return
  }

  try {
    await form.value?.validate()
  } catch (e) {
    console.error(e);
    ElMessage.warning($t('form_check_rejected'))
    return
  }

  const params = JSON.parse(JSON.stringify(state.formConfig))
  const propMap: any = {}
  params.columnConfig.forEach((item: any) => propMap[item.prop] = item)
  params.columnConfig.forEach((item: any) => {
    item.prop = item.propAlias || item.prop
    // 变更关联属性值
    item.visibleProp = propMap[item.visibleProp]?.propAlias
    if (!params.multilingual) {
      const value = item[`label${lang}`]
      item.labelch = value
      item.labelen = value
      item.labeljp = value
    }
  })
  params.columnConfig = JSON.stringify(params.columnConfig)
  params.auditConfig = JSON.stringify(params.auditConfig)

  try {
    await saveWorkFlowConfig(params)
    ElMessage.success($t('common_0090'))
    // router.push({ name: 'WorkflowList' })
    // router.push({path:'list'})
    router.push({path:'workflowList'})
    useTagsViewStore().delView(currentTag)
    // routesStore.closeTag(currentRoute.name)
  } catch (e) {
    console.error(e)
  } finally {
    state.activeTab = FormConfigType.COLUMN
  }

}

const loading = ref(false)

onActivated(() => {
  const { formId } = props
  if (formId) {
    loading.value = true
    replace(state.formConfig, {
      optionType: '1',
      optionValue: '',
      needAudit: true,
      columnConfig: [],
      auditConfig: defaultFlow(),
    })
    replace(state.columnData, {})
    replace(state.auditData, {})
    getDetail(formId).then(({ data }: any) => {
      data.columnConfig = JSON.parse(data.columnConfig).map((item: any) => ({ ...item, saved: item.saved || moment().isAfter(data.startDate) ? true:false }))
      data.auditConfig = JSON.parse(data.auditConfig)
      data.activated = data.formVersion !== '1' || moment().isAfter(data.startDate)
      if (!props.disabled && moment().isAfter(data.startDate)) {
        data.startDate = undefined
        data.endDate = undefined
      }
      replace(state.formConfig, data)
      return
    }).finally(() => loading.value = false)
  }
})
</script>
