<template>
  <CusDialog
    :show="show"
    :title="titleCpt"
    @onClose="$emit('update:show', false)"
    width="80%"
    height="80%"
    @onSubmit="onSubmit"
    :loading="state.loading"
  >
    <div class="__cus-dialog-form">
      <CusForm ref="ref_form" label-width="100px">
        <CusFormColumn
          :span="24"
          required
          type="textarea"
          v-model:param="state.valueStr"
          :rows="12"
          :rules="[
              {
                handle: (val) => {
                  try {
                    const a = JSON.parse(val)
                    return true
                  } catch (e) {
                    return false
                  }
                },
                message: 'JSON结构异常'
              }
          ]"
        />
      </CusForm>
      <div class="params-content">
        <div class="request-params">
          <div style="margin-bottom: 10px; display: flex">
            <CusButton type="main" title="新增" @click="state.params.data.push({type: '2'})"/>
            <div class="tips" style="margin: 0 10px">
              为了保证数据结构准确，提交时将默认触发“<span style="color: var(--cus-main-color)">逆向生成JSON结构</span>”
            </div>
            <CusButton type="main" title="正向解析JSON结构" style="margin-left: auto" @click="jsonToTable"/>
            <CusButton type="main" title="逆向生成JSON结构" @click="tableToJson"/>
          </div>
          <CusTable
            :data="state.params.data"
            :table-head="state.params.tableHead"
            :no-page="true"
          >
            <template #key-column-value="{scope}">
              <CusFormColumn
                class="__cus-table-form-column"
                :span="24"
                v-model:param="scope.row.key"
              />
            </template>
            <template #type-column-value="{scope}">
              <CusFormColumn
                class="__cus-table-form-column"
                :span="24"
                v-model:param="scope.row.type"
                link="select"
                :options="DictionaryStore.fzCsList"
                :clearable="false"
                @change="(val) => scope.row.value = ''"
              />
            </template>
            <template #value-column-value="{scope}">
              <CusFormColumn
                class="__cus-table-form-column"
                :span="24"
                v-model:param="scope.row.value"
              />
            </template>
            <template #label-column-value="{scope}">
              <CusFormColumn
                class="__cus-table-form-column"
                :span="24"
                v-model:param="scope.row.label"
              />
            </template>
            <template #do-column-value="{scope}">
              <CusButton type="table-del" @click="state.params.data.splice(scope.$index, 1)"/>
            </template>
          </CusTable>
        </div>
      </div>
    </div>
  </CusDialog>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, nextTick, reactive, ref, watch} from "vue";
import {useDictionaryStore} from "@/stores";
import {ElMessage, ElMessageBox} from "element-plus";

const emit = defineEmits(['update:show', 'complex'])
const {proxy} = getCurrentInstance()
const DictionaryStore = useDictionaryStore()
const props = defineProps({
  show: {default: false},
  transfer: {}
 })
const state: any = reactive({
  valueStr: '',
  loading: false,
  params: {
    tableHead: [
      {value: "key", label: "键名"},
      {value: "type", label: "类型", width: 160},
      {value: "value", label: `取值（动态取值：\$['变量名']）`},
      {value: "label", label: "含义"},
      {value: "do", label: "操作", width: 120, fixed: 'right'},
    ],
    data: []
  }
})
const ref_form = ref()
const titleCpt = computed(() => {
  let t = '复杂参数规则'
  return t
})
const onSubmit = () => {
  if (state.params.data.length === 0) {
    ElMessage.error('请完善参数信息！')
    return
  }
  tableToJson()
  setTimeout(() => {
    let flag = state.params.data.every(v => proxy.$util.isValue(v.key) && proxy.$util.isValue(v.value) && proxy.$util.isValue(v.label))
    if (!flag) {
      ElMessage.error('请完善参数信息！')
      return
    }
    ref_form.value.submit().then(() => {
      ElMessageBox.confirm("是否提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      } as any).then(() => {
        emit('update:show', false)
        emit('complex', {
          str: state.valueStr,
          table: state.params.data
        })
      }).catch(() => {})
    }).catch((e) => {
      ElMessage({
        message: e[0].message,
        grouping: true,
        type: 'warning',
      })
    })
  }, 100)
}
const jsonToTable = () => {
  try {
    const json = JSON.parse(state.valueStr)
    state.params.data = []
    Object.entries(json).forEach(([k, v]) => {
      state.params.data.push({
        key: k, value: typeof v === 'object' ? JSON.stringify(v): v, type: '2'
      })
    })
  } catch (e) {
    ElMessage.error('JSON结构异常！')
  }
}
const tableToJson = () => {
  const obj = {}
  state.params.data.forEach(v => {
    obj[v.key] = v.value
  })
  state.valueStr = JSON.stringify(obj)
}
watch(() => props.show, (n) => {
  if (n) {
    state.loading = false
    initDictionary()
    state.valueStr = props.transfer.value ? JSON.parse(JSON.stringify(props.transfer.value)) : ''
    state.params.data = props.transfer.valueTable ? [...props.transfer.valueTable] : []
    nextTick(() => {
      ref_form.value.reset()
    })
  }
})
const initDictionary = () => {
  DictionaryStore.initDict('fz_cs')
}
</script>

<style lang="scss" scoped>
.__cus-dialog-form {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.params-content {
  flex: 1;
  overflow: hidden;
  .request-params {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}
.tips {
  background-color: rgba(var(--cus-main-color-rgb), 0.1);
  border-radius: 6px;
  padding: 7px;
  margin-bottom: 10px;
  width: 100%;
}
</style>
