<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <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-select
                v-model="shpLabelSelected[item]"
                multiple
                filterable
                default-first-option
                placeholder="标签字段配置">
                <el-option
                  v-for="dict in shpItemArr[item] "
                  :key="dict"
                  :label="dict"
                  :value="dict"
                />
            </el-select>

            <div v-for="(tdtitem,index) in shpLabelSelected[item]" :key="index" >
              {{ tdtitem }}:
              <!-- <el-input v-model="shpLabelSelected[item][index]" placeholder="标签注记配置" /> -->
              <el-input v-model="shpLabelConfig[item][index].FontColor" placeholder="标签注记配置2" >
                <template #prepend>
                  <el-button >字体颜色</el-button>
                </template>
                <template #append>
                  颜色选择器：
                  <el-color-picker v-model="shpLabelConfig[item][index].FontColor" show-alpha />
                  <!-- <el-button >px</el-button> -->
                </template>
              </el-input>
              <el-input v-model="shpLabelConfig[item][index].MaxDis" placeholder="标签注记配置3" >
                <template #prepend>
                  <el-button >最大可见距离：</el-button>
                </template>
                <template #append>
                  <el-button >米</el-button>
                </template>
              </el-input>
              <el-input v-model="shpLabelConfig[item][index].Scale[0]" placeholder="标签注记配置4" >
                <template #prepend>
                  <el-button >最远处缩放：</el-button>
                </template>
                <template #append>
                  <el-button >倍</el-button>
                </template>
              </el-input>
              <el-input v-model="shpLabelConfig[item][index].Scale[1]" placeholder="标签注记配置5" >
                <template #prepend>
                  <el-button >最近处缩放：</el-button>
                </template>
                <template #append>
                  <el-button >倍</el-button>
                </template>
              </el-input>
            </div>

        <!-- {{ shpItemArr[item] }} -->
        <!-- <div v-for="item2 in formData.itemShp" :key="item2">
          <el-button/>
        </div> -->

      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DisbursementApi, DisbursementVO } from '@/api/bpm/disbursement'
import {getSimpleGisNameList} from "@/api/layer/gisname";
import {getgisAttr} from "@/api/layer/gisname";

/** 资金拨付流程表	 表单 */
defineOptions({ name: 'DisbursementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

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: {},
  shpLabelSelected : {},
  itemZoomSet:[]
})
const formRules = reactive({
  userId: [{ required: true, message: '申请人的用户编号不能为空', trigger: 'blur' }],
  reason: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '申请类型不能为空', trigger: 'change' }],
  funding: [{ required: true, message: '申请总金额不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '审批结果不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const datagisname = ref([]);

const shpItemArr = ref({});
const shpItemSelected = ref({});
const shpLabelSelected = ref({});
const tdtArray = ref([""]);
const shpLabelConfig = ref({});
//[109.2,31.277,156777.64156853,0]

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];
          if(!shpLabelSelected.value[element] )
            shpLabelSelected.value[element] = [] || shpLabelSelected.value[element];
        });
      });
    }
    // let ltyShpHelper = newValue.value.itemShp;
    // ltyShpHelper.forEach(lsp => {
    //   console.log(getgisAttr(lsp));
    //   // shpItemArr.value[element] = getgisAttr(element);
    // });
  },
  {
    deep:true,
    immediate:true
  }
)

watch(()=>shpLabelSelected.value,
  async (newValue)=>{
    console.log("ltyWatching_shpLabelSelected",newValue);
    if(newValue){
      for(let shp in newValue){
        // console.log(shp);
        // console.log(newValue[shp]);
        // shpLabelConfig.value[shp] = shpLabelSelected.value[shp].map((shpLabelSelectedMapper)=>{
        //   return {
        //     Font: shpLabelSelectedMapper+" "+"Font空的！",
        //     MaxDis:800,
        //     Scale:1
        //   }
        // })
        shpLabelConfig.value[shp] = shpLabelConfig.value[shp] || [];
        shpLabelSelected.value[shp].forEach((shpLabelSelectedMapper,index)=>{
          shpLabelConfig.value[shp][index] = shpLabelConfig.value[shp][index] || {};
          shpLabelConfig.value[shp][index].FontColor =  shpLabelConfig.value[shp][index].FontColor || "rgba(255, 255, 255, 1)";
          shpLabelConfig.value[shp][index].MaxDis = shpLabelConfig.value[shp][index].MaxDis || 800 ;
          shpLabelConfig.value[shp][index].Scale = shpLabelConfig.value[shp][index].Scale || [0.1,1] ;
        })
        console.log("ltyDebuging",[newValue,shpLabelConfig.value[shp]])
        // {Font: shp+" "+"Font空的！",MaxDis:800, Scale:1};
      }
    }
  },
  {
    deep:true,
    immediate:true
  }
)

const gisnamedatalist = async () => {
  datagisname.value = await getSimpleGisNameList();
  console.log(datagisname.value);
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DisbursementApi.getDisbursement(id)
      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 = {};

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

      //NOTE - 解析JSON中的shpLabelSelected
      let shpLabelInfo = JSON.parse(formData.value.shpLabelInfo);
      console.log("ltyLabelInfo",shpLabelInfo)
      let shpLabelSelected_helper = {};

      for(let shp in shpLabelInfo){
        shpLabelSelected_helper[shp] = shpLabelInfo[shp].map((shpLabelInfoMapper)=>{return shpLabelInfoMapper.shpLabel});
        shpLabelConfig.value[shp] = shpLabelInfo[shp].map((shpLabelInfoMapper)=> {
            return shpLabelInfoMapper.config
        })
      }


      Object.assign(shpItemSelected.value, shpItemSelected_helper );
      Object.assign(shpLabelSelected.value, shpLabelSelected_helper );

      console.log("lty162",[formData.value,shpItemSelected.value,JSON.parse(formData.value.shpItemInfo) ]);
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    //NOTE -  处理 shp属性配置
    let shpItemSelected_helper = {}
    for(let item in shpItemSelected.value){
      shpItemSelected_helper[item] = shpItemSelected.value[item].map((shpItem)=>{
        return {
          shpItem: shpItem
        };
      });
    }

    //NOTE -  处理 shp属性配置
    let shpLabelSelected_helper = {};
    for(let item in shpLabelSelected.value){
      shpLabelSelected_helper[item] = shpLabelSelected.value[item].map((shpLabel,index)=>{
        console.log("ltyLabel_Updata",shpLabelConfig.value[item])
        return {
          shpLabel: shpLabel,
          config: shpLabelConfig.value[item][index] || {}
        };
      });
    }

    const data = {
      ... formData.value ,
      shpItemInfo: shpItemSelected_helper,
      itemBaseLayer: tdtArray.value,
      shpLabelInfo: shpLabelSelected_helper,

    };// as unknown as DisbursementVO
    console.log("Submiting",data);
    // formLoading.value = false
    // return;
    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: {},
    shpLabelSelected : {},
    itemBaseLayer:undefined,
    itemZoomSet:[]
  }
  formRef.value?.resetFields()
  gisnamedatalist()
}
</script>
