<script setup name="addPlan">
import { h, onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { create, edit, detail, filterProjects } from '@/http/apis/performanceEvaluation/evaluationPlan'
import ProjectListDialog from '@/pages/performanceEvaluation/evaluationPlan/components/projectListDialog.vue'
import ApplicationListDialog from '@/pages/performanceEvaluation/evaluationPlan/components/applicationListDialog.vue'
import store from '@/store'
import { auditDetail } from '@/http/apis/performanceEvaluation/performanceApprove'
import { templateTypeList } from '@/http/apis/performanceEvaluation/indicatorTemplate'
const { projectTypeOptions } =
    store.dictStore.globalDicts || {},
  formData = ref({
    target: ['1'],
    projects: [],
    applications: []
  }),
  fromRef = ref(),
  router = useRouter(),
  route = useRoute(),
  { proxy } = getCurrentInstance(),
  moneyValidator = (rule, value, callback) => {
    if (!value) callback()
    if (!/^\d+(\.\d{1,6})?$/.test(value)) {
      callback('请输入正确格式，最多保留六位小数')
    } else if (value * 1 >= 100000000) {
      callback('请输入正确格式，小于100000000')
    } else if (formData.value.startAmount && formData.value.endAmount && formData.value.startAmount > formData.value.endAmount) {
      callback('项目金额范围的起始金额不能大于最终金额')
    } else {
      callback()
    }
  },
  rateValidator = (rule, value, callback) => {
    if (!value) callback()
    if (formData.value.selfAppraisalScoreRate && formData.value.reAppraisalScoreRate && (formData.value.selfAppraisalScoreRate + formData.value.reAppraisalScoreRate !== 100)) {
      callback('自评分和复评分比例相加必须等于100')
    } else {
      callback()
    }
  },
  yearValidator = (rule, value, callback) => {
    if (!value) callback()
    if (formData.value.projectYearStart > formData.value.projectYearEnd) {
      callback('开始年份必须小于等于结束年份')
    } else {
      callback()
    }
  },
  rules = {
    name: [
      { required: true, message: '请输入' }
    ],
    startSelfDays: [
      { required: true, message: '请输入' }
    ],
    completeSelfDays: [
      { required: true, message: '请输入' }
    ],
    target: [{ required: true, message: '请选择' }],
    projectYear: [{ required: true, message: '请选择' }],
    projectYearStart: [{ required: true, message: '请选择' }, { validator: yearValidator, trigger: 'blur' }],
    projectYearEnd: [{ required: true, message: '请选择' }, { validator: yearValidator, trigger: 'blur' }],
    startAmount: [{ required: true, message: '请输入' }, { validator: moneyValidator, trigger: 'blur' }],
    endAmount: [{ required: true, message: '请输入' }, { validator: moneyValidator, trigger: 'blur' }],
    reAppraisalRate: [{ required: true, message: '请选择' }],
    selfAppraisalScoreRate: [{ required: true, message: '请输入' }, { validator: rateValidator, trigger: 'blur' }],
    reAppraisalScoreRate: [{ required: true, message: '请输入' }, { validator: rateValidator, trigger: 'blur' }],
    projects: [{ required: true, message: '至少需要一个项目' }],
    applications: [{ required: true, message: '请添加' }]
  },

  column = reactive([
    {
      label: '序号',
      type: 'index',
      width: '60'
    },
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '预算年度',
      key: 'projectYear',
      prop: 'projectYear'
    },
    {
      label: '项目金额',
      key: 'declareAmount',
      prop: 'declareAmount'
    },
    {
      label: '申报单位',
      key: 'buildOrgName',
      prop: 'buildOrgName'
    },
    {
      label: '项目类型',
      key: 'projectType',
      prop: 'projectType',
      render: row => h('span', projectTypeOptions[row.projectType] || '-')
    },
    {
      label: '模板类型',
      key: 'templateType',
      prop: 'templateType',
      render: row => h('span', templateTypeListData.value?.find(i => i.id === row.templateType)?.name || '-')
    },
    // {
    //   label: '是否评价',
    //   key: 'isAppraisal',
    //   slot: 'isAppraisal'
    // },
    {
      label: '是否复评',
      key: 'isReAppraisal',
      slot: 'isReAppraisal'
    },
    {
      label: '操作',
      slot: 'action',
      width: '70',
      fixed: 'right'
    }
  ]),
  column1 = reactive([
    {
      label: '序号',
      type: 'index',
      width: '60'
    },
    {
      label: '应用名称',
      key: 'relatedExistsApplication',
      prop: 'relatedExistsApplication',
      minWidth: 150,
      render: row => h('span', row.relatedExistsApplication || row.applicationName),
      showOverflowTooltip: true
    },
    {
      label: '申报单位',
      key: 'buildOrgName',
      prop: 'buildOrgName'
    },
    {
      label: '应用类型',
      key: 'applicationType',
      prop: 'applicationType'
    },
    {
      label: '应用领域',
      key: 'bizDomain',
      prop: 'bizDomain',
      render: row => h('span', row.bizDomain)
    },
    {
      label: '发布端',
      key: 'publishSide',
      prop: 'publishSide'
    },
    {
      label: '操作',
      slot: 'action',
      width: '70',
      fixed: 'right'
    }
  ]),
  tableListRef = ref(),
  tableListRef1 = ref(),
  // 添加项目
  projectListDialogData = reactive({
    visible: false,
    data: undefined,
    params: undefined
  }),
  addProject = () => {
    const form = []
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('projectYear', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('startAmount', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('endAmount', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    Promise.all([...form]).then(() => {
      projectListDialogData.visible = true
      projectListDialogData.data = formData.value?.projects || []
      const years = []
      for (let i = formData.value.projectYearStart * 1; i <= formData.value.projectYearEnd * 1; i++) {
        years.push(i)
      }
      projectListDialogData.params = {
        projectYear: years.join(','),
        startAmount: formData.value.startAmount,
        endAmount: formData.value.endAmount
      }
    })
  },
  closePorject = () => {
    projectListDialogData.visible = false
  },
  getProjectData = (data) => {
    formData.value.projects = data.map(i => {
      return {
        ...i
      }
    })
    closePorject()
  },
  delData = (index, name) => {
    formData.value[name].splice(index, 1)
  },
  // 添加应用
  appListDialogData = reactive({
    visible: false,
    data: undefined,
    params: {
      regionCode: route.query.regionId,
      status: 30001,
      appraisalId: route.query.id
    }
  }),
  addApp = () => {
    appListDialogData.visible = true
    appListDialogData.data = formData.value?.applications || []
  },
  closeApp = () => {
    appListDialogData.visible = false
  },
  getAppData = (data) => {
    formData.value.applications = data.map(i => {
      return {
        ...i,
        appId: i.id
      }
    })
    closeApp()
  },
  auditId = ref(),
  submit = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async valid => {
      if (valid) {
        const years = []
        for (let i = formData.value.projectYearStart * 1; i <= formData.value.projectYearEnd * 1; i++) {
          years.push(i)
        }
        const postData = {
          ...formData.value,
          auditId: auditId.value || undefined,
          projectYear: years.join(','),
          target: formData.value.target.join(','),
          projects: formData.value.target.includes('1') && formData.value?.projects?.map(i => {
            return {
              ...i,
              id: i.projectId || i.id
            }
          }) || undefined,
          applicationIds: formData.value.target.includes('2') && formData.value?.applications?.map(i => i.appId) || undefined,
          applications: undefined,
          auditInfo: undefined,
          auditStatus: undefined,
          auditStatusName: undefined,
          auditMessage: undefined,
          projectYearStart: undefined,
          projectYearEnd: undefined
        }
        if (route.query.id) {
          await edit(postData)
        } else {
          await create(postData)
        }
        proxy.$message.success('提交成功')
        router.go(-1)
      }
    })
  },
  getDetail = async () => {
    if (route.query.auditId) {
      const res = await auditDetail(route.query.auditId)
      const year = res.data.appraisalDetail?.projectYear.toString().split(',')
      formData.value = {
        ...res.data?.appraisalDetail,
        projectYearStart: year?.[0] || '',
        projectYearEnd: year?.[year.length - 1] || '',
        target: res.data?.appraisalDetail.target.split(',')
      }
      if (res.data.auditStatus === 3) {
        auditId.value = res.data.id
      }
    } else {
      const res = await detail(route.query.id)
      const year = res.data?.projectYear.toString().split(',')
      formData.value = {
        ...res.data,
        projectYearStart: year?.[0] || '',
        projectYearEnd: year?.[year.length - 1] || '',
        target: res.data.target.split(',')
      }
      if (res.data.auditInfo.auditStatus === 3) {
        auditId.value = res.data.auditInfo.id
      }
    }
  },
  // 清空项目
  resetProjects = () => {
    if (formData.value.projects?.length) {
      formData.value.projects = []
    }
  },
  // 筛选项目
  searchProjects = async () => {
    const form = []
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('projectYear', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('startAmount', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('endAmount', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    form.push(new Promise((resolve, reject) => {
      fromRef.value.validateField('reAppraisalRate', (valid) => {
        if (valid) {
          resolve()
        } else {
          reject(false)
        }
      })
    }))
    Promise.all([...form]).then(async () => {
      const years = []
      for (let i = formData.value.projectYearStart * 1; i <= formData.value.projectYearEnd * 1; i++) {
        years.push(i)
      }
      const res = await filterProjects({
        projectYear: years.join(','),
        startAmount: formData.value.startAmount,
        endAmount: formData.value.endAmount,
        reAppraisalRate: formData.value.reAppraisalRate,
        appraisalId: route.query.id || undefined
      })
      formData.value.projects = res.data.map(i => {
        return {
          ...i,
          isAppraisal: true
        }
      })
    })
  },
  templateTypeListData = ref(),
  getTemplateTypeList = async () => {
    const res = await templateTypeList()
    templateTypeListData.value = res.data
  }
onMounted(() => {
  getTemplateTypeList()
  if (route.query.id || route.query.auditId) {
    getDetail()
  }
})
</script>
<template>
  <div class="mainBox">
    <el-card>
      <el-form
        ref="fromRef"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width=""
        label-suffix=":"
        scroll-to-error
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="formData.name" maxlength="50" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="自评时间" required>
              <div class="flex items-center">
                <span>项目终验后</span>
                <el-form-item
                  label-width="0"
                  style="margin-bottom: 0;width: 60px"
                  class="mx-4"
                  prop="startSelfDays"
                >
                  <el-input-number
                    v-model="formData.startSelfDays"
                    :min="0"
                    :controls="false"
                    @mousewheel.prevent
                  />
                </el-form-item>
                <span>天后开始自评，</span>
                <el-form-item
                  label-width="0"
                  style="margin-bottom: 0;width: 60px"
                  class="mx-4"
                  prop="completeSelfDays"
                >
                  <el-input-number
                    v-model="formData.completeSelfDays"
                    :min="0"
                    :controls="false"
                    @mousewheel.prevent
                  />
                </el-form-item>
                <span>天内需完成自评</span>
              </div>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="自评时间" prop="selfAppraisalTimes">-->
          <!--              <el-date-picker-->
          <!--                v-model="formData.selfAppraisalTimes"-->
          <!--                type="daterange"-->
          <!--                :editable="false"-->
          <!--                format="YYYY-MM-DD"-->
          <!--                value-format="YYYY-MM-DD"-->
          <!--                range-separator="-"-->
          <!--                start-placeholder="开始时间"-->
          <!--                end-placeholder="结束时间"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="复评时间" prop="reAppraisalTimes">-->
          <!--              <el-date-picker-->
          <!--                v-model="formData.reAppraisalTimes"-->
          <!--                type="daterange"-->
          <!--                :editable="false"-->
          <!--                format="YYYY-MM-DD"-->
          <!--                value-format="YYYY-MM-DD"-->
          <!--                range-separator="-"-->
          <!--                start-placeholder="开始时间"-->
          <!--                end-placeholder="结束时间"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="核查时间" prop="verificationTimes">-->
          <!--              <el-date-picker-->
          <!--                v-model="formData.verificationTimes"-->
          <!--                type="daterange"-->
          <!--                :editable="false"-->
          <!--                format="YYYY-MM-DD"-->
          <!--                value-format="YYYY-MM-DD"-->
          <!--                range-separator="-"-->
          <!--                start-placeholder="开始时间"-->
          <!--                end-placeholder="结束时间"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="评价对象" prop="target">
              <el-checkbox-group v-model="formData.target">
                <el-checkbox label="1">项目</el-checkbox>
                <el-checkbox label="2">应用</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="formData.target.includes('1')">
          <p class="font-bold mb-8">项目选择</p>
          <el-row>
            <el-col :span="12">
              <div class="flex">
                <el-form-item label="预算年度" prop="projectYearStart">
                  <el-date-picker
                    v-model="formData.projectYearStart"
                    type="year"
                    placeholder="开始年份"
                    format="YYYY"
                    value-format="YYYY"
                    @change="resetProjects"
                  />
                </el-form-item>
                <span>&nbsp;~&nbsp;</span>
                <el-form-item label-width="0" prop="projectYearStart">
                  <el-date-picker
                    v-model="formData.projectYearEnd"
                    type="year"
                    placeholder="结束年份"
                    format="YYYY"
                    value-format="YYYY"
                    @change="resetProjects"
                  />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="24" class="mb-18">
              <div class="flex items-center text-14">
                <el-form-item
                  label="项目金额（范围）"
                  style="margin-bottom: 0"
                  prop="startAmount"
                >
                  <el-input-number
                    v-model="formData.startAmount"
                    clearable
                    :controls="false"
                    placeholder="请输入起始金额"
                    @mousewheel.prevent
                    @change="resetProjects"
                  />
                </el-form-item><span>&nbsp;万元&nbsp;&le;&nbsp;项目金额&nbsp;&lt;&nbsp;</span>
                <el-form-item label-width="0" style="margin-bottom: 0" prop="endAmount">
                  <el-input-number
                    v-model="formData.endAmount"
                    clearable
                    :controls="false"
                    placeholder="请输入结束金额"
                    @mousewheel.prevent
                    @change="resetProjects"
                  />
                </el-form-item><span>&nbsp;万元</span>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="项目复评占比"
                prop="reAppraisalRate"
              >
                <div class="flex w-full">
                  <el-input-number
                    v-model="formData.reAppraisalRate"
                    clearable
                    :controls="false"
                    placeholder="请输入"
                    :max="100"
                    :min="0"
                    :precision="0"
                    @mousewheel.prevent
                    @change="resetProjects"
                  />&nbsp;%
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="mb-18">
              <div class="flex items-center text-14 w-full">
                <el-form-item
                  label="最终评分公式"
                  style="margin-bottom: 0"
                  prop="selfAppraisalScoreRate"
                >
                  <el-input-number
                    v-model="formData.selfAppraisalScoreRate"
                    class="width-150"
                    clearable
                    :controls="false"
                    placeholder="请输入"
                    :precision="0"
                    :max="100"
                    :min="0"
                    @mousewheel.prevent
                  />
                </el-form-item>&nbsp;%自评分&nbsp;+&nbsp;
                <el-form-item label-width="0" style="margin-bottom: 0" prop="reAppraisalScoreRate">
                  <el-input-number
                    v-model="formData.reAppraisalScoreRate"
                    class="width-150"
                    clearable
                    :controls="false"
                    :precision="0"
                    :max="100"
                    :min="0"
                    placeholder="请输入"
                    @mousewheel.prevent
                  />
                </el-form-item>&nbsp;%复评分
              </div>
            </el-col>
          </el-row>
          <div class="mb-8 flex">
            <el-button
              icon="plus"
              plain
              type="primary"
              @click="searchProjects"
            >筛选项目</el-button>
            <el-button
              icon="plus"
              plain
              type="primary"
              @click="addProject"
            >添加项目</el-button>
          </div>
          <el-form-item label-width="0" prop="projects">
            <table-list
              ref="tableListRef"
              :column="column"
              :pagination="false"
              :data="formData.projects"
              :empty-temp="false"
              class="flex-1 mb-16"
            >
              <template #isAppraisal="{scope}">
                <el-switch v-model="scope.row.isAppraisal" />
              </template>
              <template #isReAppraisal="{scope}">
                <el-switch v-model="scope.row.isReAppraisal" />
              </template>
              <template #action="{scope}">
                <a v-if="!(scope.row.selfAppraisalScoreTime&&scope.row.selfAppraisalTotalScore)" class="text-danger" @click="delData(scope.$index,'projects')">删除</a>
              </template>
            </table-list>
          </el-form-item>
        </template>
        <el-row v-if="false" :gutter="24">
          <el-col :span="24">
            <el-form-item label="评价项目" prop="projects">
              <table-list
                ref="tableListRef"
                :column="column"
                :pagination="false"
                :data="formData.projects"
                :empty-temp="false"
                class="flex-1"
              >
                <template #isReAppraisal="{scope}">
                  <el-switch v-model="scope.row.isReAppraisal" />
                </template>
                <template #action="{scope}">
                  <a class="text-danger" @click="delData(scope.$index,'projects')">删除</a>
                </template>
              </table-list>
              <div>
                <el-button
                  icon="plus"
                  plain
                  type="primary"
                  class="mt-16"
                  @click="addProject"
                >添加项目</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.target.includes('2')" :gutter="24">
          <el-col :span="24">
            <el-form-item label="评价应用" prop="applications">
              <table-list
                ref="tableListRef1"
                :column="column1"
                :pagination="false"
                :data="formData.applications"
                :empty-temp="false"
                class="flex-1"
              >
                <template #action="{scope}">
                  <a class="text-danger" @click="delData(scope.$index,'applications')">删除</a>
                </template>
              </table-list>
              <div>
                <el-button
                  icon="plus"
                  plain
                  type="primary"
                  class="mt-16"
                  @click="addApp"
                >添加应用</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="footer">
      <el-button
        type="primary"
        @click="submit(fromRef)"
      >
        提交
      </el-button>
      <el-button @click="router.go(-1)">取消</el-button>
    </div>
    <project-list-dialog
      :visible="projectListDialogData.visible"
      :data="projectListDialogData.data"
      :params="projectListDialogData.params"
      :template-type-list-data="templateTypeListData"
      @close="closePorject"
      @get-project-data="getProjectData"
    />
    <application-list-dialog
      :visible="appListDialogData.visible"
      :data="appListDialogData.data"
      :params="appListDialogData.params"
      @close="closeApp"
      @get-app-data="getAppData"
    />
  </div>
</template>
