<template>
  <ProjectDetails :isEdit="false" :projectid="projectid" />
  <el-divider content-position="left">项目信息变更字段</el-divider>
  选择变更字段：<a-select v-model:value="selectValue" style="width: 30%" placeholder="选择变更字段" :options="options"
    @change="changeOptions" />
  <div v-if="showupload">
    <el-divider content-position="left">上传文件</el-divider>
    <el-form-item label="上传文件:">
      <el-upload class="upload-demo" ref="upload" action :http-request="httpRequest" :before-upload="beforeUpload"
        :on-exceed="handleExceed" :limit="1" :on-remove="removeFile">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">文件大小且不超过500M</div>
      </el-upload>
    </el-form-item>
  </div>
  <el-divider content-position="left">字段新值</el-divider>
  <BasicForm @register="registerchangeFieldForm" @submit="handleSubmit" />

</template>
<script lang="ts" name="Detailpage" setup>
import { defineProps, onMounted, ref, reactive } from 'vue'
import { } from './projectInfo.data';

import { getChangeFieldManageDict, submitFieldchange, getRemainingMoneyinfo, queryProjectInfoById } from './projectInfo.api'
import ProjectDetails from "../../ProcessApprovalSubPage/component/ProjectDetails.vue"
import { useForm, BasicForm } from '@/components/Form';
import { formSchemas } from './projectInfo.data';
import { message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { FormSchema } from '@/components/Form';

let dataTo = defineProps(["projectid", "stage", "IsModify", "fatherid"])
let emit = defineEmits(["close"])
console.log("dataTo11111", dataTo)
let selectValue = ref()
let options = ref()
let showupload = ref(false)
let fileList = reactive<Array<any>>([]);
let showFormSchema: FormSchema[] = []
onMounted(async () => {
  options.value = await getChangeFieldManageDict()
})
//
const [registerchangeFieldForm, { getFieldsValue, validate, setFieldsValue, resetSchema, appendSchemaByField }] = useForm({

  resetButtonOptions: { text: '取消' },

  submitButtonOptions: { text: '提交' },
  //查询列占比 24代表一行 取值范围 0-24
  actionColOptions: { span: 14 },

  resetFunc: customResetFunc,
  labelCol: { style: { width: '120px' } },
  wrapperCol: { style: { width: 'auto' } },
  // disabled:true
})

function httpRequest(option) {
  fileList.push(option)
}
function removeFile(option) {
  for (let i = 0; i < fileList.length; i++) {
    if (fileList[i].file.name == option.name) {
      fileList.splice(i, 1)
    }
  }
  console.log(fileList, option)

}
// 上传前处理
function beforeUpload(file) {
  let fileSize = file.size
  const FIVE_M = 500 * 1024 * 1024;
  //大于5M，不允许上传
  if (fileSize > FIVE_M) {
    message.error("最大上传500M")
    return false
  }
  //判断文件类型，必须是xlsx格式
  // let fileName = file.name
  // let reg = /^.+(\.xlsx)$/
  // if(!reg.test(fileName)){
  //   ElMessage.error("只能上传xlsx!")
  //   return false
  // }
  return true
}
// 文件数量过多时提醒
function handleExceed() {
  message.warning("最多只能上传一个文件")
}


async function handleSubmit(record) {
  const params = new FormData()
  // 将上传文件数组依次添加到参数paramsData中
  if (fileList.length > 0) {
    fileList.forEach((x) => {
      console.log("xxxxxxxxxx", x, x.file)
      params.append('file', x.file)
    });
  }
  params.append("id", dataTo.projectid)
  params.append("fieldValue", selectValue.value)
  if (await validate) {
    let newValue = await getFieldsValue()
    Object.keys(newValue).forEach(key => {
      //如果是修改金额，则只提交金额相关的值
      if (selectValue.value == "Money" && key.includes("Money")) {
        params.append(key, newValue[key])
      } else {
        //只添加修改项有关值
        if (key == selectValue.value) {
          params.append(key, newValue[key])
        }
      }
    })
    console.log("params", params)
    await submitFieldchange(params)

    emit("close")
  }
}
async function customResetFunc() {
  emit("close")
}
async function changeOptions(value, option) {
  let formSchemasTemp = cloneDeep(formSchemas)
  //如果是子项目修改
  if (dataTo.fatherid) {
    let subres = await getRemainingMoneyinfo({
      projectId: dataTo.fatherid,//主项目id
      id: dataTo.projectid//子项目id

    })
    if (value == "Money") {
      //取出含有金额的内容，并设置最大值
      let moenyform = formSchemasTemp.filter(item => item.field.includes("Money"))
      moenyform.forEach(item => {
        item.componentProps["max"] = subres[item.field]
        showFormSchema.push(item)
      })
      resetSchema(moenyform)
      queryProjectInfoById({
        projectid: dataTo.projectid
      }).then(res => {
        setFieldsValue(res)
      })
    } else {
      formSchemasTemp.forEach(item => {
        if (item.field == value) {
          item.dynamicDisabled = false
          resetSchema(item)
        }
      })
    }
//主项目修改
  } else {
    //选择修改金额，则重置金额表单，显示之前的金额值
    if (value == "Money") {
      let moenyform = formSchemasTemp.filter(item => item.field.includes("Money"))
      resetSchema(moenyform)
      queryProjectInfoById({
        projectid: dataTo.projectid
      }).then(res => {
        setFieldsValue(res)
      })
    } else {
      formSchemasTemp.forEach(item => {
        if (item.field == value) {
          item.dynamicDisabled = false
          resetSchema(item)
        }
      })
    }
  }

  if (option.upload == "1") {
    showupload.value = true
  } else {
    showupload.value = false
    fileList.pop()

  }
  selectValue.value
}
</script>
<style></style>
