<template>
  <div class="h-full flex custormForm">
    <div class="p-5 w-60 pr-0">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col const-left">
        <el-table ref="customFormTableRef" :data="customFormTableData" border highlight-current-row
          @current-change="customFormHandleCurrentChange" style="width: 100%;height: 100%;">
          <el-table-column prop="name" label="模块" align="center" />
        </el-table>
      </div>
    </div>
    <div class="flex-1 p-5 overflow-auto">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col">
        <div class="tableHeader">
          <div>模块 - {{ currentRow.name }}</div>
          <el-button type="primary" @click="showModel()" :disabled="!currentRow.id">编辑表单</el-button>
        </div>
        <div class="flex-1 p-3" v-loading="AllLoading.elementLading">
          <GenerateForm ref="generateForm" :data="generateFormData"></GenerateForm>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="AllMobelVisible.formMobelVisible" title="创建表单" width="90vw" align-center
      :before-close="handleClose">
      <div class="createForm">
        <DesignForm ref="designForm" :basicFieldsList="letBasicFields" :advanceFieldsList="[]" :layoutFieldsList="[]" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="AllMobelVisible.formMobelVisible = false">取消</el-button>
          <el-button type="primary" @click="updateJson()" v-loading="AllLoading.createFormLoading">
            保存
          </el-button>
          <div @click="setData()">设置数据</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import { FormInstance, FormRules, ElMessageBox, ElTable } from 'element-plus'
import { DesignForm, GenerateForm, basicFields } from '@zmjs/form-design';
import { useStore } from '@/store/index'
import { post, get } from '@/utils/request';
import { GETLIST, GETLISTBYCODE, UPDATEADDOR } from './api'
import { getFromValue, resetFromValue } from '@/utils/tools'
const { routers } = useStore()
type customFormTab = {
  id: string | number,
  config: string,
  name: string,
  code: string,
}
interface createForm {
  id: string | number,
  code: string,
  name: string,
  config: string,
  companyId: string | number,
  createTime: any,
  isCurrent: string | number,
}

const globalPopup = inject<GlobalPopup>('globalPopup')
const designForm = ref<any>(null);
const generateForm = ref<any>(null)
const currentRow: any = ref({})
const customFormTableData = ref<customFormTab[]>([])
const customFormTableRef = ref<InstanceType<typeof ElTable>>()
const AllLoading = reactive({
  createFormLoading: false,
  elementLading: false
})
const AllMobelVisible = reactive({
  formMobelVisible: false
})

const listByCodeArr = ref<any>({})
const generateFormData = ref<any>({
  list: [],
  config: {}
})
const createForm = reactive<createForm>({
  id: '',
  code: '',
  name: '',
  config: '',
  companyId: '',
  createTime: '',
  isCurrent: ''
})


// const letBasicFields:Partial<typeof basicFields> = ["input", "select", "textarea", "time", "date"]
const letBasicFields: any = ["input", "select", "textarea", "time", "date"]

function updateJson() {
  createForm.config = JSON.stringify(designForm.value.getJson())
  let newForm = getFromValue(createForm)
  AllLoading.createFormLoading = true
  post(UPDATEADDOR, { ...newForm }).then((res: any) => {
    AllLoading.createFormLoading = false
    if(res.code != 'ok') {
      globalPopup?.showError(res.msg)
      return
    }
    globalPopup?.showSuccess ('保存成功')
    getListByCode()
    AllMobelVisible.formMobelVisible = false
  }).catch((err: any) => {
    AllLoading.createFormLoading = false
    console.log(err)
  })
}

function getList() {
  post(GETLIST, {}).then((res: any) => {
    customFormTableData.value = res.data.map((item: any) => {
      return {
        id: item.id,
        config: item.config,
        name: item.name,
        code: item.code
      }
    })
  }).catch((err: any) => {
    console.log(err)
  })
}

function getListByCode() {
  AllLoading.elementLading = true
  get(`${GETLISTBYCODE}/${currentRow.value.code}`, {}).then((res: any) => {
    listByCodeArr.value = res.data[0]
    generateFormData.value = JSON.parse(res.data[0].config)
    setTimeout(() => {
      AllLoading.elementLading = false
    }, 1000)
  }).catch((_err: any) => {
    setTimeout(() => {
      AllLoading.elementLading = false
    }, 500)
  })
}

function showModel() {
  const { id, code, name, companyId, createTime, isCurrent, config } = listByCodeArr.value
  Object.assign(createForm, {
    id,
    code,
    name,
    companyId,
    isCurrent,
    config
  })
  AllMobelVisible.formMobelVisible = true
  setTimeout(() => {
    designForm.value.setJson(JSON.parse(config))
    // designForm.value.setJson(JSON.parse(localStorage.getItem('threadDataJson') || ''))
    // designForm.value.setJson(JSON.parse(localStorage.getItem('business') || ''))
    // designForm.value.setJson(JSON.parse(localStorage.getItem('tasks') || ''))
  }, 500)
}

function customFormHandleCurrentChange(val: any) {
  currentRow.value = val;
  getListByCode()
}

function handleClose(done: any) {
  done();
}

function setData() {
  // let data = JSON.parse(localStorage.getItem('threadDataJson') || '')
  // let data = JSON.parse(localStorage.getItem('business') || '')
  // let data = JSON.parse(localStorage.getItem('tasks') || '')
  let data = JSON.parse(localStorage.getItem('product') || '')
  data.list.forEach((element: any) => {
    element.allDisable = true
  });
  console.log(data, '<=== 赋值好的')
  designForm.value.setJson(data)
}

onMounted(() => {
  getList()
});
</script>
  
<style lang="scss" scoped>
.custormForm {
  .createForm {
    width: 100%;
    height: 65vh;
  }

  .tableHeader {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background-color: #F5F7FA;
  }

  .el-dialog__body {
    padding: 0 !important;
  }
}
</style>