package com.ruoyi.web.controller.oa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oa.domain.CmcAssessContent;
import com.ruoyi.oa.domain.CmcAssessContentWork;
import com.ruoyi.oa.service.ICmcAssessContentService;
import com.ruoyi.oa.service.ICmcAssessContentWorkService;
import com.ruoyi.oa.service.ICmcProjectService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.oa.domain.CmcAssess;
import com.ruoyi.oa.service.ICmcAssessService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考核表Controller
 * 
 * @author cmc
 * @date 2024-01-09
 */
@RestController
@RequestMapping("/oa/assess")
public class CmcAssessController extends BaseController
{
    @Autowired
    private ICmcAssessService cmcAssessService;
    @Autowired
    private ICmcAssessContentService cmcAssessContentService;
    @Autowired
    private ICmcAssessContentWorkService cmcAssessContentWorkService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ICmcProjectService cmcProjectService;
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询考核表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcAssess cmcAssess)
    {
        startPage();
        List<CmcAssess> list = cmcAssessService.selectCmcAssessList(cmcAssess);
        return getDataTable(list);
    }

    /**
     * 导出考核表列表
     */
    @Log(title = "考核表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcAssess cmcAssess)
    {
        List<CmcAssess> list = cmcAssessService.selectCmcAssessList(cmcAssess);
        ExcelUtil<CmcAssess> util = new ExcelUtil<CmcAssess>(CmcAssess.class);
        util.exportExcel(response, list, "考核表数据");
    }

    /**
     * 获取考核表详细信息
     */
    @GetMapping(value = "/{assessId}")
    public AjaxResult getInfo(@PathVariable("assessId") String assessId)
    {
        CmcAssess cmcAssess = cmcAssessService.selectCmcAssessByAssessId(assessId);
        List<CmcAssessContent> cmcAssessContentList = cmcAssessContentService.selectCmcAssessContentByContentId(assessId);
        List<CmcAssessContentWork> cmcAssessContentWorkList = cmcAssessContentWorkService.selectCmcAssessContentWorkByWorkId(assessId);
        JSONObject formData = new JSONObject();
        Long userId = 0L;
        if (cmcAssess == null)
            userId = getLoginUser().getUserId();
        else
            userId = cmcAssess.getUserId();
        formData.put("userId", userId);
        formData.put("nickName", userService.selectUserById(userId).getNickName());
        formData.put("deptName", deptService.selectDeptById(userService.selectUserById(userId).getDeptId()).getDeptName());
        formData.put("postGroup", userService.selectUserPostGroup(userService.selectUserById(userId).getUserName()));
        formData.put("pmLevel", dictDataService.selectDictLabel("sys_user_pmlevel", userService.selectUserById(userId).getPmLevel()));
        if (userService.selectUserById(userId).getTitles() != null && !userService.selectUserById(userId).getTitles().equals("")) {
            String[] titles = userService.selectUserById(userId).getTitles().split(",");
            List<String> titleList = new ArrayList<>();
            for (String title : titles)
                titleList.add(dictDataService.selectDictLabel("sys_user_titles", title));
            formData.put("titles", String.join(",", titleList));
        }
        else
            formData.put("titles", userService.selectUserById(userId).getTitles());
        formData.put("remark", userService.selectUserById(userId).getRemark());
        formData.put("entryDate", userService.selectUserById(userId).getEntryDate());
        formData.put("age", userService.selectUserById(userId).getAge());
        formData.put("assessId", assessId);
        if (cmcAssess != null) {
            formData.put("assessTime", cmcAssess.getAssessTime());
            formData.put("projectId", cmcAssess.getProjectId());
            if (cmcAssess.getProjectId() != null && !cmcAssess.getProjectId().equals("")){
                formData.put("projectNumber", cmcProjectService.selectCmcProjectByProjectId(cmcAssess.getProjectId()).getProjectNumber());
                formData.put("projectName", cmcProjectService.selectCmcProjectByProjectId(cmcAssess.getProjectId()).getProjectName());
            }
            formData.put("otherWork", cmcAssess.getOtherWork());
            formData.put("selfAssess", cmcAssess.getSelfAssess());
            formData.put("deptAssesser", cmcAssess.getDeptUser().getNickName());
            formData.put("deptAssessment", cmcAssess.getDeptAssessment());
            formData.put("deptAdvice", cmcAssess.getDeptAdvice());
            formData.put("deptTime", cmcAssess.getDeptTime() != null ? DateUtils.dateTime(cmcAssess.getDeptTime()) : cmcAssess.getDeptTime());
            formData.put("managerAssesser", cmcAssess.getManagerUser().getNickName());
            formData.put("managerAssessment", cmcAssess.getManagerAssessment());
            formData.put("managerAdvice", cmcAssess.getManagerAdvice());
            formData.put("managerTime", cmcAssess.getManagerTime() != null ? DateUtils.dateTime(cmcAssess.getManagerTime()) : cmcAssess.getManagerTime());
            for (CmcAssessContent cmcAssessContent: cmcAssessContentList) {
                formData.put("role" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getRole());
                formData.put("familiar" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getFamiliar());
                formData.put("workload" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getWorkload());
                formData.put("remark" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getRemark());
                formData.put("skill" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getSkill());
                formData.put("quality" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getQuality());
                formData.put("assessment" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getAssessment());
                formData.put("advice" + cmcAssessContent.getContentId().substring(19), cmcAssessContent.getAdvice());
            }
            for (CmcAssessContentWork cmcAssessContentWork: cmcAssessContentWorkList) {
                formData.put("f" + cmcAssessContentWork.getWorkId().substring(19), cmcAssessContentWork.getWorkLoad());
            }
        }
        return success(formData);
    }

    /**
     * 新增考核表
     */
    @Log(title = "考核表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcAssess cmcAssess)
    {
        return toAjax(cmcAssessService.insertCmcAssess(cmcAssess));
    }

    /**
     * 提交考核表
     */
    @Log(title = "考核表", businessType = BusinessType.INSERT)
    @PostMapping( "/submit")
    public AjaxResult submit(@RequestParam("form")String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcAssess cmcAssess = new CmcAssess();
        cmcAssess.setUserId(getLoginUser().getUserId());
        cmcAssess.setFillTime(DateUtils.getNowDate());
        cmcAssess.setAssessId(formDataJson.getString("formId"));
        cmcAssess.setAssessType(formDataJson.getString("assessType"));
        cmcAssessService.insertCmcAssess(cmcAssess);
        for (String key : formDataJson.keySet()) {
            //必填项
            if (key.length() == 5 && key.startsWith("f") && !formDataJson.get(key).equals("")) {
                CmcAssessContentWork cmcAssessContentWork = new CmcAssessContentWork();
                cmcAssessContentWork.setWorkId(cmcAssess.getAssessId() + key.substring(1));
                cmcAssessContentWork.setWorkLoad(formDataJson.getString(key));
                cmcAssessContentWorkService.insertCmcAssessContentWork(cmcAssessContentWork);
                CmcAssessContent cmcAssessContent = new CmcAssessContent();
                cmcAssessContent.setContentId(cmcAssess.getAssessId() + key.substring(1,3));
                cmcAssessContentService.insertCmcAssessContent(cmcAssessContent);
            }
        }
        for (String key : formDataJson.keySet()) {
            if (formDataJson.get(key) != null) {
                if (key.equals("projectId"))
                    cmcAssess.setProjectId(formDataJson.getString(key));
                if (key.equals("assessTime"))
                    cmcAssess.setAssessTime(formDataJson.getDate(key));
                if (key.equals("otherWork"))
                    cmcAssess.setOtherWork(formDataJson.getString(key));
                if (key.equals("selfAssess"))
                    cmcAssess.setSelfAssess(formDataJson.getString(key));
                if (key.startsWith("role") && !Objects.equals(formDataJson.get(key), new JSONArray())) {
                    JSONArray roleArray = new JSONArray();
                    if (!formDataJson.getString(key).equals("") && !formDataJson.getString(key).contains(",")) {
                        roleArray.add(formDataJson.getString(key));
                    }
                    else
                        roleArray = formDataJson.getJSONArray(key);
                    String roles = StringUtils.join(roleArray, ",");
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(cmcAssess.getAssessId() + key.substring(4)).get(0);
                    cmcAssessContent.setRole(roles);
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("familiar")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(cmcAssess.getAssessId() + key.substring(8)).get(0);
                    cmcAssessContent.setFamiliar(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("remark") && key.length() > 6) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(cmcAssess.getAssessId() + key.substring(6)).get(0);
                    cmcAssessContent.setRemark(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
            }
        }
        cmcAssessService.updateCmcAssess(cmcAssess);
        return AjaxResult.success("提交考核表成功");
    }

    /**
     * 修改考核表
     */
    @Log(title = "考核表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcAssess cmcAssess)
    {
        return toAjax(cmcAssessService.updateCmcAssess(cmcAssess));
    }

    /**
     * 修改考核表
     */
    @Log(title = "考核表", businessType = BusinessType.UPDATE)
    @PutMapping( "/modify")
    public AjaxResult modify(@RequestParam("form")String formData)
    {
        JSONObject formDataJson = JSONObject.parse(formData);
        CmcAssess cmcAssess = cmcAssessService.selectCmcAssessByAssessId(formDataJson.getString("assessId"));
        cmcAssess.setProjectId(formDataJson.getString("projectId"));
        cmcAssess.setAssessType(formDataJson.getString("assessType"));
        cmcAssess.setAssessTime(formDataJson.getDate("assessTime"));
        cmcAssess.setOtherWork(formDataJson.getString("otherWork"));
        cmcAssess.setSelfAssess(formDataJson.getString("selfAssess"));
        if (formDataJson.getString("deptAssessment") != null && formDataJson.getString("managerAssessment") == null) {
            cmcAssess.setDeptAssesser(getLoginUser().getUserId());
            cmcAssess.setDeptAssessment(formDataJson.getString("deptAssessment"));
            cmcAssess.setDeptAdvice(formDataJson.getString("deptAdvice"));
            cmcAssess.setDeptTime(new Date());
        }
        if (formDataJson.getString("managerAssessment") != null) {
            cmcAssess.setManagerAssesser(getLoginUser().getUserId());
            cmcAssess.setManagerAssessment(formDataJson.getString("managerAssessment"));
            cmcAssess.setManagerAdvice(formDataJson.getString("managerAdvice"));
            cmcAssess.setManagerTime(new Date());
        }
        //判断是否删除某项考核工作
        List<CmcAssessContentWork> cmcAssessContentWorks = cmcAssessContentWorkService.selectCmcAssessContentWorkByWorkId(formDataJson.getString("assessId"));
        List<String> oldCmcAssessContentWorkIds = new ArrayList<>();
        List<String> newCmcAssessContentWorkIds = new ArrayList<>();
        for (CmcAssessContentWork cmcAssessContentWork : cmcAssessContentWorks) {
            oldCmcAssessContentWorkIds.add(cmcAssessContentWork.getWorkId());
        }
        for (String key : formDataJson.keySet()) {
            if (key.length() == 5 && key.startsWith("f") && !formDataJson.get(key).equals(""))
                newCmcAssessContentWorkIds.add(key.substring(1));
        }
        for (String id : oldCmcAssessContentWorkIds) {
            if (!newCmcAssessContentWorkIds.contains(id.substring(19)))
                cmcAssessContentWorkService.deleteCmcAssessContentWorkByWorkId(id);
        }
        for (String key : formDataJson.keySet()) {
            if (formDataJson.get(key) != null) {
                if (key.startsWith("role") && !Objects.equals(formDataJson.get(key), new JSONArray())) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(4)).get(0);
                    JSONArray roleArray = new JSONArray();
                    if (!formDataJson.getString(key).equals("") && !formDataJson.getString(key).contains(",")) {
                        roleArray.add(formDataJson.getString(key));
                    }
                    else
                        roleArray = formDataJson.getJSONArray(key);
                    String roles = StringUtils.join(roleArray, ",");
                    cmcAssessContent.setRole(roles);
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.length() == 5 && key.startsWith("f") && !formDataJson.get(key).equals("")) {
                    List<CmcAssessContentWork> cmcAssessContentWorkList = cmcAssessContentWorkService.selectCmcAssessContentWorkByWorkId(formDataJson.getString("assessId") + key.substring(1));
                    if (cmcAssessContentWorkList.size() > 0) { //某项考核工作更改工作量
                        cmcAssessContentWorkList.get(0).setWorkLoad(formDataJson.getString(key));
                        cmcAssessContentWorkService.updateCmcAssessContentWork(cmcAssessContentWorkList.get(0));
                    }
                    else { //新增一项考核工作
                        CmcAssessContentWork cmcAssessContentWork = new CmcAssessContentWork();
                        cmcAssessContentWork.setWorkId(formDataJson.getString("assessId") + key.substring(1));
                        cmcAssessContentWork.setWorkLoad(formDataJson.getString(key));
                        cmcAssessContentWorkService.insertCmcAssessContentWork(cmcAssessContentWork);
                    }
                }
                if (key.startsWith("familiar")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(8)).get(0);
                    cmcAssessContent.setFamiliar(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("remark") && key.length() > 6) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(6)).get(0);
                    cmcAssessContent.setRemark(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("workload")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(8)).get(0);
                    cmcAssessContent.setWorkload(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("skill")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(5)).get(0);
                    cmcAssessContent.setSkill(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("quality")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(7)).get(0);
                    cmcAssessContent.setQuality(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("assessment")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(10)).get(0);
                    cmcAssessContent.setAssessment(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
                if (key.startsWith("advice")) {
                    CmcAssessContent cmcAssessContent = cmcAssessContentService.selectCmcAssessContentByContentId(formDataJson.getString("assessId") + key.substring(6)).get(0);
                    cmcAssessContent.setAdvice(formDataJson.getString(key));
                    cmcAssessContentService.updateCmcAssessContent(cmcAssessContent);
                }
            }
        }
        cmcAssessService.updateCmcAssess(cmcAssess);
        return AjaxResult.success("修改考核表成功");
    }

    /**
     * 删除考核表
     */
    @Log(title = "考核表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{assessIds}")
    public AjaxResult remove(@PathVariable String[] assessIds)
    {
        return success(cmcAssessService.deleteCmcAssessByAssessIds(assessIds));
    }
}
