<template>
  <ContentWrap>
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
      >
        <el-form-item label="天地图配置">
          <el-input  v-for="(tdtitem,index) in tdtArray" :key="index" v-model="tdtArray[index]" >
            <template #append>
              <el-button @click="tdtArray.splice(index,1) ">删除</el-button>
            </template>
          </el-input>
          <el-button @click="tdtArray.push('') ">添加+</el-button>
        </el-form-item>

        <el-form-item label="地图初始位置">
          <div>
            <el-input v-model="formData.itemZoomSet[0]">
              <template #prepend>
                经度
              </template>
            </el-input>
            <el-input v-model="formData.itemZoomSet[1]">
              <template #prepend>
                维度
              </template>
            </el-input>
            <el-input v-model="formData.itemZoomSet[2]">
              <template #prepend>
                高度
              </template>
            </el-input>
            <el-input v-model="formData.itemZoomSet[3]">
              <template #prepend>
                倾角
              </template>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="数据绑定" prop="itemShp">
          <!-- <el-input v-model="formData.itemShp" placeholder="请输入项目相关shp上传（保存url，可null）" />
            -->
          <el-select
              v-model="formData.itemShp"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择项目相关图层">
            <el-option
                v-for="dict in datagisname"
                :key="dict.id"
                :label="dict.shpName"
                :value="dict.shpName"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="item" v-for="(item) in formData.itemShp" :key="item" >
          图层属性配置：
          <el-select
              v-model="shpItemSelected[item]"
              multiple
              filterable
              default-first-option
              placeholder="图层属性配置">
            <el-option
                v-for="dict in shpItemArr[item] "
                :key="dict"
                :label="dict"
                :value="dict"
            />
          </el-select>
          <el-button @click="fieldsConfig(item)">配置表单</el-button>
          <div v-if="shpItemField[item] != null">
            <form-create :inFor="true" :rule="shpItemField[item]" v-model:api="fApi"  :option="shpItemConf[item]"/>
          </div>
<!--          <div v-else-if="shpItemField[item] != null && shpItemConf[item] == null">-->
<!--            <form-create :rule="shpItemField[item]" v-model:api="fApi"  :option="options"/>-->
<!--          </div>-->
        </el-form-item>
        <el-form-item>
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        </el-form-item>
      </el-form>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <twinEditor @submit-filed="handleSubmitFiled" ref="twinEditorRef"/>

</template>
<script lang="ts" setup>/** 资金拨付流程表	 表单 */
import {getgisAttr, getSimpleGisNameList} from "@/api/layer/gisname";
import {DisbursementApi} from "@/api/bpm/disbursement";
import twinEditor from "./editor/index.vue"
import {string} from "vue-types";

defineOptions({ name: 'BpmDisbursementDetail' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { query } = useRoute() // 查询参数
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  userId: undefined,
  reason: undefined,
  processInstanceId: undefined,
  file: undefined,
  id: undefined,
  type: undefined,
  funding: undefined,
  status: undefined,
  specialLoansFile: undefined,
  itemName: undefined,
  itemType: undefined,
  itemBelong: undefined,
  itemShp: undefined,
  itemImage: undefined,
  fundingApplicationFile: undefined,
  itemDisbursementStatus: undefined,
  shpItemSelected: {},
  itemZoomSet:[],
  shpItemField:{},
  shpItemConf:{}
})
const options = ref( {
  submitBtn: { show: false },
  resetBtn: { show: false },
})
const shpItemField = ref({});
const shpItemConf = ref({});
const formRef = ref() // 表单 Ref
const datagisname = ref([]);
const shpItemArr = ref({});
const shpItemSelected = ref({});
const tdtArray = ref([""]);
const twinEditorRef = ref()
const fApi = ref(null);

watch(() => formData.value.itemShp,
    async (newValue) => {
      // console.log("ltyWatching",newValue);
      if(newValue){
        (await newValue).forEach(element => {
          // console.log(element);
          getgisAttr(element).then((res)=> {
            // console.log("ltyWriting",[element,res])
            shpItemArr.value[element] = res
            if(!shpItemSelected.value[element] )
              shpItemSelected.value[element] = [] || shpItemSelected.value[element];
          });
        });
      }
    },
    {
      deep:true,
      immediate:true
    }
)

const newShpItemSelected = computed(() => {
  return JSON.stringify(shpItemSelected.value)
})
watch(
    newShpItemSelected,
    async (newValue, oldValue) => {
      let newObj = JSON.parse(newValue);
      let oldObj = JSON.parse(oldValue);

      for (let shp in newObj) {
        if (shp) {
          let addedKeys: string[] = [];
          let removedKeys: string[] = [];

          if(!Array.isArray(shpItemConf.value[shp])){
            shpItemConf.value[shp] = options.value;
          }
          console.log(shpItemConf.value[shp])
          const newEntries = Array.isArray(newObj[shp]) ? newObj[shp] : [];
          const oldEntries = Array.isArray(oldObj[shp]) ? oldObj[shp] : [];
          // 找出新增的字段
          for (let newItem of newEntries) {
            if (!oldEntries.includes(newItem)) {
              addedKeys.push(newItem);
            }
          }

          // 找出减少的字段
          for (let oldItem of oldEntries) {
            if (!newEntries.includes(oldItem)) {
              removedKeys.push(oldItem);
            }
          }

          if (!Array.isArray(shpItemField.value[shp])) {
            shpItemField.value[shp] = [];
          }
          if (addedKeys.length > 0) {
            addedKeys.forEach(addedKey => {
              const newItem = generateJsonTemplate([addedKey]);
              if (newItem) {
                const exists = shpItemField.value[shp].some(item => {
                  return item["field"] === newItem[0]["field"]; // 假设“field”是用于比较的属性
                });
                // console.log(exists)
                if (!exists) {
                  shpItemField.value[shp].push(newItem[0]);
                }
              }
            });
          }
          // 处理移除的字段
          for (let removedKey of removedKeys) {
            shpItemField.value[shp] = shpItemField.value[shp].filter(item => {
              return removedKey !== item["field"]; // 保留没有匹配的item
            });
          }

        }
      }
    },
    {
      deep: true,
      immediate: false,
    }
);
const generateJsonTemplate = (fields ) => {
  // 为每个不存在的字段生成新的对象
  return fields.map(field => ({
    "type": "input",
    "field": field,
    "title": field,
    "info": "",
    "$required": false,
    "_fc_drag_tag": "input",
    "hidden": false,
    "display": true,
  }));
};
const gisnamedatalist = async () => {
  datagisname.value = await getSimpleGisNameList();
  // console.log(datagisname.value);
}


/** 初始化 */
onMounted(async () => {
  resetForm()
  // 修改时，设置数据
  if (query.id) {
    formLoading.value = true
    try {
      formData.value = await DisbursementApi.getDisbursement(query.id)
      console.log(formData.value)
      tdtArray.value = formData.value.itemBaseLayer || [""];
      formData.value.itemZoomSet = formData.value.itemZoomSet || [109.2,31.277,156777.64156853,0];

      //NOTE - 解析JSON中的shpItemSelected
      let shpItemInfo = JSON.parse(formData.value.shpItemInfo);
      let shpItemSelected_helper = {};
      shpItemField.value = formData.value.shpItemField;
      shpItemConf.value = formData.value.shpItemConf;


      for(let shp in shpItemInfo){
        shpItemSelected_helper[shp] = shpItemInfo[shp].map((shpItemInfoMapper)=>{return shpItemInfoMapper.shpItem});
      }
      Object.assign(shpItemSelected.value, shpItemSelected_helper );

      // console.log("lty162",[formData.value,shpItemSelected.value,JSON.parse(formData.value.shpItemInfo) ]);
    } finally {
      formLoading.value = false
    }
  }
})
const fieldsConfig = ( item: any  ) => {
  twinEditorRef.value.open(item,shpItemField.value[item],shpItemConf.value[item])
}

const handleSubmitFiled = async (shpItem :any,fields : any , conf :any)=>{

  shpItemField.value[shpItem] = fields;
  shpItemConf.value[shpItem] = conf;
}

const submitForm = async () => {
  // 校验表单
  // await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  console.log('ltyDSubmitFrom',formData.value);
  try {
    //NOTE -  处理 shp属性配置
    let shpItemSelected_helper = {}
    for(let item in shpItemSelected.value){
      shpItemSelected_helper[item] = shpItemSelected.value[item].map((shpItem)=>{
        return {
          shpItem: shpItem
        };
      });
    }
    const data = {
      ... formData.value ,
      shpItemInfo: shpItemSelected_helper,
      shpLabelInfo: JSON.parse(formData.value.shpLabelInfo) || {},
      itemBaseLayer: tdtArray.value,
      shpItemField:shpItemField.value,
      shpItemConf:shpItemConf.value
    };
    console.log('ltyDSubmitFrom',data);
    if (formType.value === 'create') {
      await DisbursementApi.createDisbursement(data)
      message.success(t('common.createSuccess'))
    } else {
      await DisbursementApi.updateDisbursement(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    reason: undefined,
    processInstanceId: undefined,
    file: undefined,
    id: undefined,
    type: undefined,
    funding: undefined,
    status: undefined,
    specialLoansFile: undefined,
    itemName: undefined,
    itemType: undefined,
    itemBelong: undefined,
    itemShp: undefined,
    itemImage: undefined,
    fundingApplicationFile: undefined,
    itemDisbursementStatus: undefined,
    shpItemSelected: {},
    itemBaseLayer:undefined,
    itemZoomSet:[],
    shpItemField:{},
    shpItemConf:{}
  }
  formRef.value?.resetFields()
  gisnamedatalist()
}
</script>
