<template>
  <div v-loading="loading">
    <el-form :model="formData" ref="form" class="query-form" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="分摊名称" prop="shareName">
            <el-input v-model="formData.shareName" placeholder="请输入分摊名称" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分摊月份" prop="apportionmentMonth">
            <el-date-picker
                v-model="formData.apportionmentMonth"
                type="month"
                format="YYYY-MM"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择月"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-table v-if="showTable" :data="formData.tableData" style="width: 100%">
          <el-table-column prop="projectId" label="项目名称" width="230">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.projectId?'1':rules.projectId">
                <el-select v-model="scope.row.projectId" placeholder="请选择项目名称" clearable>
                  <el-option
                      v-for="item in nameOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="researchPersonnel" label="研发人员" width="230">
            <template #default="scope">
              <el-form-item prop="researchPersonnel">
                {{ scope.row.researchPersonnelName ? scope.row.researchPersonnelName : currentReachPerson.name }}
                <el-button @click="showPersonnelPicker(scope.row,scope.$index)">
                  {{ scope.row.researchPersonnelName || currentReachPerson.name ? '更改' : '请选择研发人员' }}
                </el-button>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="wagesPayable" label="应发工资" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.wagesPayable?'1':rules.wagesPayable">
                <el-input-number v-model="scope.row.wagesPayable" placeholder="请输入应发工资" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="performance" label="绩效" width="175">
            <template #default="scope">
              <el-form-item prop="time">
                <el-input-number v-model="scope.row.performance" placeholder="请输入绩效" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="reserveFund" label="公积金" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.reserveFund?'1':rules.reserveFund">
                <el-input-number v-model="scope.row.reserveFund" placeholder="请输入公积金" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="socialSecurity" label="社保" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.socialSecurity?'1':rules.socialSecurity">
                <el-input-number v-model="scope.row.socialSecurity" placeholder="请输入社保" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="annuity" label="年金" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.annuity?'1':rules.annuity">
                <el-input-number v-model="scope.row.annuity" placeholder="请输入年金" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="workday" label="工作日(天)" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.workday?'1':rules.workday">
                <el-input-number v-model="scope.row.workday" placeholder="请输入工作日" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="researchDuration" label="研发时长(天)" width="175">
            <template #default="scope">
              <el-form-item prop="time" :rules="scope.row.researchDuration?'1':rules.researchDuration">
                <el-input-number v-model="scope.row.researchDuration" placeholder="请输入研发时长" :controls="false"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="oper" label="操作">
            <template #default="scope">
              <el-button type="primary" @click="handleCopy(scope.row)" link style="font-size: 18px">复制</el-button>
              <el-button type="primary" @click="handleDelete(scope.$index)" link style="font-size: 18px">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <user-picker :multiple="false" ref="userPicker" title="请选择研发人员" v-model:value="userList" @ok="selected"
                 :setNullToSelectList="true"/>

    <div style="width:100%;text-align: center;padding: 10px">
      <el-button type="primary" @click="handleAdd" link style="font-size: 18px">添加一行</el-button>
    </div>
    <div class="approval-record">
      <div class="approval-title">
        <baseTitle title="审批记录" v-if="processDiagramViewer&& opentionData?.operationList"></baseTitle>
        <div v-else></div>
        <div style="display: flex;align-items: center;justify-content: flex-end;">
          <div class="base-title">流程图</div>
          <el-switch
              v-model="changeDiagram"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color:#BEA266;margin-left: 10px"
          />
        </div>
      </div>
      <div class="process">
        <operation-render
            v-if="processDiagramViewer&& opentionData?.operationList && opentionData?.operationList.length > 0&&!changeDiagram"
            :operation-list="opentionData?.operationList"
            :state="opentionData.state"/>
        <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>
      </div>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="routerName==='Share/add'" @click="handleSubmit(form)">提交</el-button>
      <el-button color="#DED0B2" v-else @click="handleResubmit(form)">重新提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import {ElNotification} from "element-plus";
import {useTagsView} from '@/stores/tagsview.js'
import {
  addAllocation,
  getAllocationDetail,
  getAllocationProcess,
  getResearchUser,
  getProjectOption,
  editAllocation,
  getAllocationDetailList
} from "@/api/expense-manage";
import {useProcessStore} from '@/stores/processStore.js';
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import {ref} from "vue";

import UserPicker from "@/views/workflow/process/common/UserPicker.vue";

const userList = ref([])
const changeDiagram = ref(false)
const rules = reactive({
  shareName: [{required: true, message: '请输入分摊名称', trigger: 'blur'}],
  apportionmentMonth: [{required: true, message: '请选择月份', trigger: 'blur'}],
  projectId: [{required: true, message: '请选择项目名称', trigger: 'blur'}],
  // researchPersonnel: [{required: true, message: '请选择研发人员', trigger: 'blur'}],
  wagesPayable: [{required: true, message: '请输入应发工资', trigger: 'blur'}],
  performance: [{required: true, message: '请输入绩效', trigger: 'blur'}],
  reserveFund: [{required: true, message: '请输入公积金', trigger: 'blur'}],
  socialSecurity: [{required: true, message: '请输入社保', trigger: 'blur'}],
  annuity: [{required: true, message: '请输入年金', trigger: 'blur'}],
  workday: [{required: true, message: '请输入工作日', trigger: 'blur'}],
  researchDuration: [{required: true, message: '请输入研发时长', trigger: 'blur'}],
})
const processStore = useProcessStore()
const opentionData = ref()
const processInstanceData = ref()
const processDiagramViewer = ref(false)
const loading = ref(false)
const showTable = ref(true)
const route = useRoute()
const router = useRouter()
const routerName = ref(router.currentRoute.value.name)
const tagsViewStore = useTagsView()
const formData = ref({
  tableData: [
    {
      projectId: '',
      projectName: '',
      researchPersonnel: '',
      wagesPayable: null,
      performance: null,
      reserveFund: null,
      socialSecurity: null,
      annuity: null,
      workday: '21.75',
      researchDuration: null,
    }
  ]
})
const userPicker = ref()
const form = ref()
const currentReachPerson = ref({})
const currentRow = ref()
const currentIndex = ref()
const nameOptions = ref([])
const researchOptions = ref([])
const showPersonnelPicker = (row, index) => {
  currentRow.value = row
  currentIndex.value = index
  userPicker.value.showUserPicker()
}
const selected = (select) => {
  for (const selectElement of select) {
    currentReachPerson.value = selectElement
  }
  formData.value.tableData.forEach((item, index) => {
    if (index == currentIndex.value) {
      item.researchPersonnel = currentReachPerson.value.id
      item.researchPersonnelName = currentReachPerson.value.name
    }
  })
}
const getResearchOptions = async () => {
  const res = await getResearchUser()
  researchOptions.value = res.data
}
const getProjectOptions = async () => {
  const res = await getProjectOption()
  nameOptions.value = res.data
}
const getProjectName = (id) => {
  let label = ''
  nameOptions.value.forEach(item => {
    if (item.value === id) {
      label = item.label
    }
  })
  return label
}
const handleAdd = () => {
  let row = {
    projectId: '',
    projectName: '',
    researchPersonnel: '',
    wagesPayable: null,
    performance: null,
    reserveFund: null,
    socialSecurity: null,
    annuity: null,
    workday: '21.75',
    researchDuration: null,
  }
  formData.value.tableData.push(row)
}
const handleCopy = (row) => {
  let copyObj = {
    projectId: row.projectId,
    projectName: '',
    researchPersonnel: row.researchPersonnel,
    wagesPayable: row.wagesPayable,
    performance: row.performance,
    reserveFund: row.reserveFund,
    socialSecurity: row.socialSecurity,
    annuity: row.annuity,
    workday: '21.75',
    researchDuration: row.researchDuration,
  }
  formData.value.tableData.push(copyObj)
}
const handleDelete = (index) => {
  formData.value.tableData.splice(index, 1)
}
const handleSubmit = (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) {
      return ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
    }
    formData.value.tableData.forEach(item => {
      item.projectName = getProjectName(item.projectId)
      if (item.performance == 0) {
        item.performance = null
      }
    })
    let params = {
      shareName: formData.value.shareName,
      apportionmentMonth: formData.value.apportionmentMonth,
      usrAllocations: formData.value.tableData,
      deploymentId: processInstanceData.value.deploymentId,
    }
    console.log('params', params, formData.value.tableData)
    const {code, msg} = await addAllocation(params)
    ElNotification({
      title: '提示',
      message: msg,
      type: code === 1000 ? 'success' : 'error'
    })
    if (code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        name: 'Expense/share'
      })
    }
  })
}
const handleResubmit = (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) {
      return ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
    }
    formData.value.tableData.forEach(item => {
      item.allocationId = formData.value.allocationId
      item.projectName = getProjectName(item.projectId)
      if (item.performance == 0) {
        item.performance = null
      }
    })
    let params = {
      allocationId: formData.value.allocationId,
      shareName: formData.value.shareName,
      apportionmentMonth: formData.value.apportionmentMonth,
      usrAllocations: formData.value.tableData,
      deploymentId: processInstanceData.value.deploymentId,
    }
    console.log('params', params)
    const {code, msg} = await editAllocation(params)
    ElNotification({
      title: '提示',
      message: msg,
      type: code === 1000 ? 'success' : 'error'
    })
    if (code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        name: 'Expense/share'
      })
    }
  })
}

const getDetailInfo = () => {
  loading.value = true
  getAllocationDetail(route.query.id).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      getDetailList()
      formData.value = res.data.formData
      opentionData.value = res.data
      loading.value = false
    }
  })
}
const getDetailList = async () => {
  let params = {
    allocationId: route.query.id
  }
  showTable.value = false
  const {code, data, msg} = await getAllocationDetailList(params)
  if (code === 1000) {
    data.rows.forEach(item => {
      item.researchPersonnel = Number(item.researchPersonnel)
    })
    formData.value.tableData = data.rows
    nextTick(() => {
      showTable.value = true
    })
  } else {
    ElNotification({
      title: '提示',
      message: msg,
      type: 'error'
    })
  }
}
const init = async () => {
  processDiagramViewer.value = false
  await getResearchOptions()
  await getProjectOptions()
  getAllocationProcess().then(res => {
    if (res.code === 1000) {
      let data = res.data
      processInstanceData.value = data
      processStore.setDesign(data)
      processStore.runningList.value = data.runningList;
      processStore.endList.value = data.endList;
      processStore.noTakeList.value = data.noTakeList;
      processStore.refuseList.value = data.refuseList;
      processStore.passList.value = data.passList;
      nextTick(() => {
        processDiagramViewer.value = true
      })
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
const handleBack = () => {
  history.back()
}
onMounted(() => {
  init()
  if (route.query.id) {
    getDetailInfo()
  }
})
</script>
<style scoped lang="scss">
:deep(.el-table--enable-row-transition) {
  .el-table__body td.el-table__cell {
    .cell {
      .el-form-item {
        margin-top: 20px;
      }
    }
  }
}
</style>
