<template>
    <hc-new-dialog v-model="addNodeModal" :title="title" widths="50rem" @save="confirmClick" @close="cancelClick">
        <el-form ref="ruleFormRef" :model="addform" :rules="rules" label-width="110px">
            <el-form-item label="节点名称" prop="nodeName">
                <el-input v-model="addform.nodeName" size="large" />
            </el-form-item>
            <!-- <el-form-item label="岗位类型" prop="postType">
          <el-select  v-model="addform.postType"  placeholder="请选择岗位" size="large" style="width:100%">
              <el-option v-for="item in JobTypeList" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="节点类型" prop="nodeType">
          <el-select  :disabled='addform.id'  v-model="addform.nodeType"  placeholder="请选择节点类型" size="large" style="width:100%">
              <el-option  v-for="item in nodeTypeList"  :key="item.value" :label="item.label"  :value="item.value"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="工程类型" prop="projectType">
          <el-select  v-model="addform.projectType"  placeholder="工程类型" size="large" style="width:100%">
          <el-option v-for="item in projectTypeList"  :key="item.value"  :label="item.label" :value="item.value"></el-option>
          </el-select>
      </el-form-item> -->


            <!-- <el-form-item  label="储存类型"  prop="storageType"  v-if="addform.nodeType==1">
          <el-select  v-model="addform.storageType"  placeholder="请选择"  size="large" style="width:100%">
              <el-option  v-for="item in storageTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
      </el-form-item> -->

            <template v-if="true">
                <el-form-item label="是否存储节点" prop="isStorageNode">
                    <el-select v-model="addform.isStorageNode" placeholder="请选择" size="large" style="width:100%">
                        <el-option v-for="item in storageNodeList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <template v-if="addform.isStorageNode == 1">
                    <el-form-item label="储存类型" prop="storageType">
                        <el-select v-model="addform.storageType" placeholder="请选择" size="large" style="width:100%">
                            <el-option v-for="item in storageTypeList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item  label="是否竣工图" prop="isBuiltDrawing">
                  <el-select v-model="addform.isBuiltDrawing" placeholder="请选择" size="large" style="width:100%">
                      <el-option v-for="item in builtDrawingList"  :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="是否接口节点" prop="isInterfaceNode">
                  <el-select v-model="addform.isInterfaceNode" placeholder="请选择" size="large" style="width:100%">
                      <el-option v-for="item in interfaceNodeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
              </el-form-item>

              <template v-if="addform.isInterfaceNode==1">
                  <el-form-item label="选择接口类型">
                      <el-select v-model="addform.interfaceType" placeholder="请选择" size="large" style="width:100%">
                          <el-option v-for="item in interfaceTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                  </el-form-item>
              </template> -->
                </template>
            </template>

            <!-- <template v-if="addform.nodeType==1">
          <el-form-item  label="关联类型" prop="associationType">
              <el-select  v-model="addform.associationType"  placeholder="请选择" size="large" style="width:100%">
                  <el-option v-for="item in associationTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
          </el-form-item>

          <template v-if="addform.associationType==1">
              <el-form-item  label="业内资料类型"  prop="majorDataType">
                  <el-checkbox-group v-model="addform.majorDataType">
                      <el-checkbox v-for="item in majorDataTypeList" :key="item.dictKey" :label="item.dictKey" name="type">{{item.dictValue}}</el-checkbox>
                  </el-checkbox-group>
              </el-form-item>
              <el-form-item  label="显示层级" prop="displayHierarchy">
                  <el-select  v-model="addform.displayHierarchy" placeholder="请选择" size="large" style="width:100%">
                      <el-option  v-for="item in displayHierarchyList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                  </el-select>
              </el-form-item>
          </template>

          <template v-if="addform.associationType==2">
              <el-form-item label="文件类型" prop="expDataType">
                  <el-checkbox-group v-model="addform.expDataType">
                      <el-checkbox v-for="item in fileTypeList" :key="item.value" :label="item.label">{{item.label}}</el-checkbox>
                  </el-checkbox-group>
              </el-form-item>
          </template>
      </template> -->
            <el-form-item label="组卷规则" prop="archiveAutoType">
                <el-select v-model="addform.archiveAutoType" placeholder="请选择" size="large" style="width:100%">
                    <el-option v-for="item in archiveAutoTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
    </hc-new-dialog>
</template>

<script setup>
import { useAppStore } from '~src/store'
import { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'
import { archiveTreeDetail, archiveTreeSave, archiveTreeUpdate, getDictionary, roletree } from '~api/other'
import archiveFileApi from '~api/archiveFile/archiveFile'
import { getArrValue, isArrItem } from 'js-fast-way'
//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },

    node: {
        type: Object,
        default: () => ({}),
    },
    show:{
      type:Boolean,
      default:false,
    },
    type: {
        type: String,
        default: '',
    },
})

//事件
const emit = defineEmits(['hide'])

const useAppState = useAppStore()

const contractId = ref(useAppState.getContractId)
const projectId = ref(props.projectId)

// 使用toRefs结构，使其具有响应式
const { node } = toRefs(props)

//监听
watch(() => [
    props.projectId,

], ([UserProjectId]) => {

    projectId.value = UserProjectId


})

watch(() => [props.show, props.type], ([newShow, newType])=>{

    //console.log(newShow,newType)
    if (newShow) {
      if (newType == 'add') {
        addNode()
      } else if (newType == 'edit') {
        editNodeModal()
      }
    } else {
      cancelClick()
      addNodeModal.value = false
    }
})

//计算属性
let title = computed(()=>{
  if (props.type == 'add') {
    return '新增'
  } else if (props.type == 'edit') {
    return '编辑'
  }
})

//渲染完成
onMounted(() => {
    //数据初始化
    //getJobTypeList()
    //major_data_type()
    //display_hierarchy()
})

//新增弹窗
let addform = ref({})
let addNodeModal = ref(false)

const addNode = async ()=>{

    //console.log(node.value.data)
    const { code, data } = await archiveTreeDetail({
        id:node.value.data.id,
    })
    if (code == 200) {
        delete data['id']
        delete data['nodeName']

        //新增的信息和父级一样
        //是否竣工图,是否接口节点。默认否
        data.isInterfaceNode = 2
        data.interfaceType = 2

        addform.value = data
        console.log(data, 'data')
        addNodeModal.value = true
        if (data.isStorageNode == 1) {
            emit('hide', {})
            window.$message.warning('存储节点下面不允许新增节点')
        }



    }
}

const cancelClick = () => {
  emit('hide', {})
  addNodeModal.value = false
}
// const confirmClick = async () => {
//     await ruleFormRef.value.validate(async (valid, fields) => {
//         if (valid) {
//             let form = {
//                 id: addform.value.id,
//                 projectId:projectId.value,
//                 parentId: node.value.data.id, //上级节点id
//                 nodeName: addform.value.nodeName,  //节点名称
//                 nodeType: addform.value.nodeType,  // 节点类型
//                 postType: addform.value.postType,  //岗位类型

//                 projectType:addform.value.projectType, //工程类型
//                 storageType:addform.value.storageType, //储存类型
//             }
//             if(addform.value.nodeType == 2){
//                 form.isStorageNode = addform.value.isStorageNode  //是否为存储节点
//                 if(addform.value.isStorageNode == 1){
//                     form.isBuiltDrawing = addform.value.isBuiltDrawing  //竣工图
//                     form.isInterfaceNode = addform.value.isInterfaceNode  //是否接口节点
//                     if(addform.value.isInterfaceNode == 1){
//                         form.interfaceType =  addform.value.interfaceType  //选择接口类型
//                     }
//                 }else{
//                     delete form.storageType
//                 }
//             }else if (addform.value.nodeType == 1){
//                 form.associationType = addform.value.associationType  //关联类型
//                 if(addform.value.associationType == 1){
//                     form.majorDataType = addform.value.majorDataType //内业资料类型
//                     form.displayHierarchy = addform.value.displayHierarchy  //显示层级
//                 }else if(addform.value.associationType == 2){
//                     // form.expDataType = addform.value.expDataType.join(',')//文件类型
//                     form.expDataType = addform.value.expDataType//文件类型
//                 }
//             }

//             await saveTreeNode(form)

//             addNodeModal.value = false
//         }
//     })
// }
const confirmClick = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            let form = {
                id: addform.value.id,
                projectId:projectId.value,
                parentId: node.value.data.id, //上级节点id
                nodeName: addform.value.nodeName, //节点名称
                nodeType: addform.value.nodeType, // 节点类型
                postType: addform.value.postType, //岗位类型
                archiveAutoType:addform.value.archiveAutoType, //组卷规则
                projectType:addform.value.projectType, //工程类型
                storageType:addform.value.storageType, //储存类型
            }

                form.isStorageNode = addform.value.isStorageNode //是否为存储节点
                if (addform.value.isStorageNode == 1) {
                    form.isBuiltDrawing = addform.value.isBuiltDrawing //竣工图
                    form.isInterfaceNode = addform.value.isInterfaceNode //是否接口节点
                    if (addform.value.isInterfaceNode == 1) {
                        form.interfaceType = addform.value.interfaceType //选择接口类型
                    }
                } else {
                    delete form.storageType
                }

                form.associationType = addform.value.associationType //关联类型
                if (addform.value.associationType == 1) {
                    form.majorDataType = addform.value.majorDataType //内业资料类型
                    form.displayHierarchy = addform.value.displayHierarchy //显示层级
                } else if (addform.value.associationType == 2) {
                    // form.expDataType = addform.value.expDataType.join(',')//文件类型
                    form.expDataType = addform.value.expDataType//文件类型
                }


            await saveTreeNode(form)
            cancelClick()
        }
    })
}

const saveTreeNode = async (form)=>{
    if (form?.majorDataType && isArrItem( form?.majorDataType)) {
        if (form.majorDataType.length > 0) {
          let das = ''
          form.majorDataType.forEach((val, key) => {
            das += val
            if (form.majorDataType.length - 1 != key) {
              das += ','
            }
          })
          form.majorDataType = das
        }
      }
      if (addform.value.id) {
        console.log(isEditsto.value, 'isEditsto.value')
        console.log(ishabvFile.value, 'ishabvFile.value')
        // await archiveTreeUpdateHandle(form)
        /*if (isEditsto.value === 1 && addform.value.isStorageNode === 2 && ishabvFile.value) {
            //是否存储类型由是改为否，要判断该节点下是否有存储文件
            window.$message.warning('当前节点下有存储文件，请迁移或删除后再变更')
        } else {
            await archiveTreeUpdateHandle(form)
        }*/
          await archiveTreeUpdateHandle(form)
      } else {
        await archiveTreeSaveHandle(form)
      }
}

const archiveTreeSaveHandle = async (form)=>{//新增
    //console.log(form);
    const { code, data } = await archiveTreeSave(form)
    //console.log(res);
    if (code == 200) {
        window.$message?.success('新增成功')
        window?.location?.reload() //刷新页面
    }
}

const archiveTreeUpdateHandle = async (form)=>{//编辑
    //console.log(form);
    const { code } = await archiveTreeUpdate(form)
    //console.log(res);
    if (code == 200) {
        window.$message?.success('修改成功')
        node.value.data.title = form.nodeName
        node.value.data.isStorageNode = form.isStorageNode
        node.value.data.storageType = form.storageType
    }
}
const ishabvFile = ref(false)
//查询该节点下有没有文件
const getTableData = async (nodeid) => {
    console.log(contractId.value, 'contractId.value')
    const { error, code, data } = await archiveFileApi.getarchiveFilePage({
        nodeIds: nodeid,
        current: 1,
        size: 20,
        total: 0,
        projectId: projectId.value,
        contractId:contractId.value,
    })
    if (!error && code === 200) {
        let dataarr = getArrValue(data['records'])
        if (dataarr.length > 0) {
            ishabvFile.value = true
        } else {
            ishabvFile.value = false
        }
    } else {
        ishabvFile.value = false
    }
}
const isEditsto = ref('')//原始为存储节点
//编辑节点
const editNodeModal = async ()=>{
    getTableData(node.value.data.id)
    const { code, data } = await archiveTreeDetail({
        id:node.value.data.id,
    })
    if (code == 200) {
        console.log(data, 'data')
        addform.value = data
        isEditsto.value = data.isStorageNode

        addNodeModal.value = true
    }
    //addform.value = node.data;

}

const ruleFormRef = ref(null)
const rules = ref({
    nodeName: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
    postType: [{ required: true, message: '请选择岗位类型', trigger: 'change' }],
    nodeType: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
    isStorageNode: [{ required: true, message: '请选择存储节点', trigger: 'change' }],
    isBuiltDrawing: [{ required: true, message: '请选择竣工图', trigger: 'change' }],
    isInterfaceNode: [{ required: true, message: '请选择接口节点', trigger: 'change' }],
    interfaceType: [{ required: true, message: '请选择接口类型', trigger: 'change' }],
    associationType: [{ required: true, message: '请选择关联类型', trigger: 'change' }],
    majorDataType: [{ required: true, message: '请选择业内资料类型', trigger: 'change' }],
    displayHierarchy: [{ required: true, message: '请选择显示层级', trigger: 'change' }],
    projectType: [{ required: true, message: '请选择工程类型', trigger: 'change' }],
    storageType: [{ required: true, message: '请选择储存类型', trigger: 'change' }],
    expDataType: [{ required: true, message: '请选择文件类型', trigger: 'change' }],
})

//类型枚举
let JobTypeList = ref([])//岗位类型枚举
const getJobTypeList = async () => {//岗位类型枚举
    const { data, code } = await roletree()
    //console.log(res);
    if (code == 200) {
        JobTypeList.value = data
    }
}
let majorDataTypeList = ref([])
const major_data_type = async () => {//内业资料类型
    const { data, code } = await getDictionary({ code: 'major_data_type' })
    //console.log(res);
    if (code == 200) {
        majorDataTypeList.value = data
    }
}
let displayHierarchyList = ref([])
const display_hierarchy = async () => {//显示层级
    const { data, code } = await getDictionary({ code: 'display_hierarchy' })
    //console.log(res);
    if (code == 200) {
        displayHierarchyList.value = data
    }
}

const nodeTypeList = [
{
    label: '关联电子原生文件',
    value: 1,
}, {
    label: '数字化上传文件',
    value: 2,
},
]//节点类型枚举
const projectTypeList = [
{
    label: '水利水电工程',
    value: 1,
}, {
    label: '公路工程',
    value: 2,
}, {
    label: '全部',
    value: 3,
},
]//工程类型枚举
const storageTypeList = [
{
    label: '普通',
    value: 1,
}, {
    label: '竣工图',
    value: 2,
}, {
    label: '计量',
    value: 3,
}, {
    label: '质检',
    value: 4,
}, {
    label: '声像',
    value: 5,
}, {
    label: '隐蔽',
    value: 6,
}, {
    label: '原材试验',
    value: 7,
}, {
    label: '管理文件',
    value: 8,
}, {
    label: '变更令',
    value: 9,
},
]//储存类型枚举
const storageNodeList = [
    {
    label: '是',
    value: 1,
    }, {
    label: '否',
    value: 2,
    },
]//存储节点枚举
const builtDrawingList = [{
    label: '是',
    value: 1,
    }, {
    label: '否',
    value: 2,
    },
]//竣工图枚举
const interfaceNodeList = [
    {
    label: '是',
    value: 1,
    }, {
    label: '否',
    value: 2,
    },
]//接口节点枚举
const interfaceTypeList = [
    {
        label: '试验接口',
        value: 1,
    }, {
        label: '计量接口',
        value: 2,
    },
]//选择接口类型枚举
const associationTypeList = [
    {
    label: '质检资料',
    value: 1,
    },
    {
    label: '试验资料',
    value: 2,
    },
    {
    label: '影像资料',
    value: 3,
    },
    {
    label: '台账资料',
    value: 4,
    }, {
    label: '首件资料',
    value: 5,
    }, {
    label: '日志文件',
    value: 6,
    },
]
const fileTypeList = [
    {
        label: '配合比',
        value: 1,
    },
    {
        label: '原材',
        value: 2,
    }, {
        label: '汇总',
        value: 3,
    }, {
        label: '设备',
        value: 4,
    }, {
        label: '外委(第三方)',
        value: 5,
    },
]
//组卷规则
const archiveAutoTypeList = [
    {
        label: '最高组卷',
        value: 1,
    },
    {
        label: '分类并卷',
        value: 2,
    }, {
        label: '单独组卷',
        value: 3,
    },
]
</script>
