<script name="applications" setup>
import { getCurrentInstance, ref, h, nextTick } from 'vue'
import AppBasicInfo from './appBasicInfo.vue'
import AppSafeInfo from './appSafeInfo.vue'
import AppResourceInfo from './appResourceInfo.vue'
import { ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import ApplicationInfo from '@/pages/declareManage/projectDeclare/declarePage/components/applicationInfo.vue'
defineProps({
  isInnovateWholeProvinceShare: {
    type: Boolean,
    default: false
  },
  isFirst: {
    type: Number,
    default: undefined
  },
  coreBusiness: {
    type: Array,
    default: () => {
      return []
    }
  }
})
const route = useRoute(),
  { proxy } = getCurrentInstance(),
  formData = ref({
    applicationList: []
  }),
  formRef = ref(),
  rules = {
    includeApplication: [
      { required: true, message: '请选择是否包含应用', trigger: 'blur' }
    ],
    applicationList: [
      { required: true, message: '请添加应用', trigger: 'blur' }
    ]
  },
  column = [
    {
      type: 'index',
      label: '序号',
      width: 60
    },
    {
      label: '应用名称',
      key: 'applicationName',
      prop: 'applicationName',
      render: row => h('span', row.applicationName || row.relatedExistsApplication?.applicationName || '')
    },
    // {
    //   label: '数改系统',
    //   key: 'digitalModification',
    //   prop: 'digitalModification',
    //   render: row => h('span', row.digitalModification?.map(i => digitalModifySystem[i]).join('，'))
    // },
    {
      label: '操作',
      slot: 'action'
    }
  ],
  // 删除应用
  deleteApplication = (index) => {
    proxy.$messageBox
      .confirm('确定要删除该项吗?', '提示！', {
        type: 'warning'
      })
      .then(() => {
        formData.value.applicationList.splice(index, 1)
      })
  },
  // 编辑、新增应用
  drawerVisible = ref(false),
  collapseModal = ref(['1', '2', '3']),
  applicationData = ref({}),
  appBasicInfoRef = ref(),
  appSafeInfoRef = ref(),
  appResourceInfoRef = ref(),
  applicationInfoRef = ref(),
  isEdit = ref(false),
  appIndex = ref(),
  editApplication = async (index, row) => {
    isEdit.value = true
    appIndex.value = index
    applicationData.value = row
    drawerVisible.value = true
    await nextTick()
    applicationInfoRef.value.clearValidate()
  },
  addApplication = async () => {
    isEdit.value = false
    applicationData.value = {}
    drawerVisible.value = true
    await nextTick()
    applicationInfoRef.value.clearValidate()
  },
  handleDrawerClose = () => {
    ElMessageBox.confirm('确定要关闭应用编辑页面吗？')
      .then(() => {
        close()
      })
      .catch(() => {
      })
  },
  close = () => {
    // appSafeInfoRef.value.clearValidate()
    // appResourceInfoRef.value.clearValidate()
    // appBasicInfoRef.value.clearValidate()
    applicationInfoRef.value.formData = {}
    applicationInfoRef.value.clearValidate()
    drawerVisible.value = false
  },
  // 暂存
  save = () => {
    if (!isEdit.value) {
      formData.value.applicationList.push({
        // ...appBasicInfoRef.value.formData,
        // ...appSafeInfoRef.value.formData,
        // ...appResourceInfoRef.value.formData
        ...applicationInfoRef.value.formData
      })
    } else {
      formData.value.applicationList[appIndex.value] = {
        // ...appBasicInfoRef.value.formData,
        // ...appSafeInfoRef.value.formData,
        // ...appResourceInfoRef.value.formData
        ...applicationInfoRef.value.formData
      }
    }
    close()
  },
  // 提交
  submitApplication = () => {
    const form = []
    // form.push(new Promise((resolve, reject) => {
    //   appBasicInfoRef.value.validForm((valid) => {
    //     if (valid) resolve()
    //   })
    // }))
    // form.push(new Promise((resolve, reject) => {
    //   appSafeInfoRef.value.validForm((valid) => {
    //     if (valid) resolve()
    //   })
    // }))
    // form.push(new Promise((resolve, reject) => {
    //   appResourceInfoRef.value.validForm((valid) => {
    //     if (valid) resolve()
    //   })
    // }))
    form.push(new Promise((resolve, reject) => {
      applicationInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    Promise.all([...form]).then(() => {
      save()
    })
  },
  // 校验
  validForm = (callback) => {
    formRef.value.validate(valid => {
      callback(valid)
    })
  },
  // 回显
  setFormData = (data) => {
    const appname = route.query.isDraft ? 'applicationList' : 'projectApplications'
    formData.value = {
      includeApplication: data.includeApplication,
      applicationList: data[appname]?.length ? data[appname].map(i => {
        return {
          ...i,
          relatedExistsApplication: i.relatedExistsApplication ? { applicationCode: i.relatedExistsApplicationCode, applicationName: i.relatedExistsApplication } : undefined
        }
      }) : []
    }
  },
  // 修改是否包含应用
  changeIncludeApplication = () => {
    formData.value.applicationList = []
  }
defineExpose({ validForm, formData, applicationData, setFormData })
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-position="right"
    label-width="180px"
    label-suffix=":"
    scroll-to-error
  >
    <el-row :gutter="40">
      <el-col :span="12">
        <el-form-item
          label="是否包含应用"
          label-width="atuo"
          prop="includeApplication"
        >
          <el-radio-group v-model="formData.includeApplication" @change="changeIncludeApplication">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col v-if="formData.includeApplication === 1" :span="24">
        <el-form-item label="包含的应用" prop="applicationList">
          <el-button
            type="primary"
            plain
            class="w-full mb-10"
            icon="Plus"
            @click="addApplication"
          >添加应用</el-button>
          <table-list
            class="w-full"
            :pagination="false"
            :data="formData.applicationList"
            :column="column"
          >
            <template #action="{scope}">
              <a
                @click="editApplication(scope.$index, scope.row)"
              >编辑</a>
              <a
                class="text-red-400"
                @click="deleteApplication(scope.$index)"
              >删除</a>
            </template>
          </table-list>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-drawer
    v-model="drawerVisible"
    title="添加应用"
    :before-close="handleDrawerClose"
    :size="1000"
  >
    <el-collapse v-if="false" v-model="collapseModal">
      <el-collapse-item name="1">
        <template #title>
          <div class="collapse-title">基本信息</div>
        </template>
        <app-basic-info
          ref="appBasicInfoRef"
          :data="applicationData"
          :is-innovate-whole-province-share="isInnovateWholeProvinceShare"
          :drawer-visible="drawerVisible"
        />
      </el-collapse-item>
      <el-collapse-item name="2">
        <template #title>
          <div class="collapse-title">安全信息</div>
        </template>
        <app-safe-info ref="appSafeInfoRef" :data="applicationData" />
      </el-collapse-item>
      <el-collapse-item name="3">
        <template #title>
          <div class="collapse-title">资源信息</div>
        </template>
        <app-resource-info ref="appResourceInfoRef" :data="applicationData" />
      </el-collapse-item>
    </el-collapse>
    <application-info
      ref="applicationInfoRef"
      :data="applicationData"
      :is-first="isFirst"
      :core-business="coreBusiness"
      :drawer-visible="drawerVisible"
    />
    <template #footer>
      <div class="applyBottomBtn flexCenter marginTop">
        <el-button @click="handleDrawerClose"> 关闭 </el-button>
        <el-button type="primary" plain @click="save"> 暂存 </el-button>
        <el-button type="primary" @click="submitApplication"> 确定 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="less">
.el-upload-list{
  width: 100%;
}
</style>
