package com.testor.module.duty.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.duty.model.domain.TSysTaskWork;
import com.testor.module.duty.model.dto.TSysTaskWorkDelParam;
import com.testor.module.duty.model.dto.TSysTaskWorkParam;
import com.testor.module.duty.model.dto.TaskWork;
import com.testor.module.duty.service.TSysTaskWorkService;
import com.testor.module.partner.model.domain.TPartnerStaff;
import com.testor.module.partner.service.TPartnerStaffService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;


/**
 * 作业活动Controller
 *
 * @author testor-framework
 * @date 2022-06-08 14:32:32
 */
@RestController
@RequestMapping("/work")
@Api(value = "TSysTaskWork", tags = "作业活动")
@Slf4j
public class TSysTaskWorkController extends SuperController {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TSysTaskWorkService tSysTaskWorkService;
    @Autowired
    private TPartnerStaffService tPartnerStaffService;

    /* Generated Method*/
//    @ApiOperation(value = "新增 作业活动", notes = "Add TSysTaskWork")
//    @PostMapping(value = "/add")
    public String addEntity(@RequestBody TSysTaskWork addRequest) throws Exception{
        return tSysTaskWorkService.addEntity(addRequest);
    }

    @ApiOperation(value = "查看详情 作业活动 ", notes = "Get TSysTaskWork By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TSysTaskWork> getById(String id) {
        BaseResponse<TSysTaskWork> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TSysTaskWork data = tSysTaskWorkService.getById(id);
            if (data != null && data.getInvolvePerson() != null && data.getInvolvePerson() != ""){
                List<String> involvePersonNames = new ArrayList<>();
                //相关方
                String[] invokePersons = data.getInvolvePerson().split(";");
                for (String stakeholder : invokePersons) {
                    String[] peoples = stakeholder.split(",");
                    if (!(peoples.length>1)) {
                        continue;
                    }
                        TPartnerStaff partnerStaff = tPartnerStaffService.getOne(new QueryWrapper<TPartnerStaff>().eq("partner_id", peoples[0]).eq("id", peoples[1]));
                        if (partnerStaff != null){
                            involvePersonNames.add(partnerStaff.getName());
                        }
                }
                data.setInvolvePersonNames(involvePersonNames);
            }


            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 作业活动 ", notes = "Update TSysTaskWork By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TSysTaskWork updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            TSysTaskWork data = BeanHelper.beanToBean(updateRequest, TSysTaskWork.class);
            boolean result = tSysTaskWorkService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "删除 作业活动 ", notes = "delete TSysTaskWork By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TSysTaskWorkDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TSysTaskWork data = new TSysTaskWork();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tSysTaskWorkService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

//    @ApiOperation(value = "批量删除作业活动", notes = "delete TSysTaskWork by batch Id")
//    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TSysTaskWorkDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TSysTaskWork> tSysTaskWorkList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TSysTaskWork data = new TSysTaskWork();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tSysTaskWorkList.add(data);
            }
            boolean result = tSysTaskWorkService.updateBatchById(tSysTaskWorkList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

//    @ApiOperation(value = "获取 作业活动 分页列表", notes = "List TSysTaskWork with page")
//    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TSysTaskWork>> listEntity(TSysTaskWorkParam param) {
        BaseResponse<BaseResponseList<TSysTaskWork>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysTaskWork> resultPage = new Page<>(page, limit);
        QueryWrapper<TSysTaskWork> queryWrapper = this.createQuery(param);
        Page<TSysTaskWork> resultList = tSysTaskWorkService.page(resultPage, queryWrapper);
        BaseResponseList<TSysTaskWork> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 作业活动 列表", notes = "添加日志的时候获取作业活动")
    @GetMapping(value = "/datas")
    public BaseResponse<List<TaskWork>> listAllEntity()throws Exception {
        BaseResponse<List<TaskWork>> baseResponse = new BaseResponse<>();
        QueryWrapper<TSysTaskWork> queryWrapper = new QueryWrapper<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        queryWrapper.eq(TSysTaskWork.COMPANY_ID, sysOrg.getOrgId());
        queryWrapper.eq(TSysTaskWork.CREATE_BY,loginUser.getUserId());
        List<TSysTaskWork> resultList = tSysTaskWorkService.list(queryWrapper);
        List<TaskWork> taskWorks = new ArrayList<>();
        resultList.stream().forEach(item->{
            TaskWork taskWork = new TaskWork();
            taskWork.setIsRiskJob(item.getIsRiskJob());
            taskWork.setActiveCategory(item.getActiveCategory());
            taskWork.setId(item.getId());
            taskWorks.add(taskWork);
        });
        baseResponse.setData(taskWorks);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSysTaskWork> createQuery(TSysTaskWorkParam queryParam) {
        QueryWrapper<TSysTaskWork> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TSysTaskWork.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TSysTaskWork.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TSysTaskWork.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TSysTaskWork.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysTaskWork.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getActiveCategory())) {
            queryWrapper.eq(TSysTaskWork.ACTIVE_CATEGORY, queryParam.getActiveCategory());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsRiskJob())) {
            queryWrapper.eq(TSysTaskWork.IS_RISK_JOB, queryParam.getIsRiskJob());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsInvolve())) {
            queryWrapper.eq(TSysTaskWork.IS_INVOLVE, queryParam.getIsInvolve());
        }
        if (StringHelper.isNotEmpty(queryParam.getInvolvePerson())) {
            queryWrapper.eq(TSysTaskWork.INVOLVE_PERSON, queryParam.getInvolvePerson());
        }
        if (StringHelper.isNotEmpty(queryParam.getSceneGuardian())) {
            queryWrapper.eq(TSysTaskWork.SCENE_GUARDIAN, queryParam.getSceneGuardian());
        }
        if (StringHelper.isNotEmpty(queryParam.getGuardianPhoto())) {
            queryWrapper.eq(TSysTaskWork.GUARDIAN_PHOTO, queryParam.getGuardianPhoto());
        }
        if (StringHelper.isNotEmpty(queryParam.getScenePhoto())) {
            queryWrapper.eq(TSysTaskWork.SCENE_PHOTO, queryParam.getScenePhoto());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsTaskApproval())) {
            queryWrapper.eq(TSysTaskWork.IS_TASK_APPROVAL, queryParam.getIsTaskApproval());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsTaskAnalysis())) {
            queryWrapper.eq(TSysTaskWork.IS_TASK_ANALYSIS, queryParam.getIsTaskAnalysis());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsSkillTell())) {
            queryWrapper.eq(TSysTaskWork.IS_SKILL_TELL, queryParam.getIsSkillTell());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsControlTask())) {
            queryWrapper.eq(TSysTaskWork.IS_CONTROL_TASK, queryParam.getIsControlTask());
        }
        if (StringHelper.isNotEmpty(queryParam.getControlReason())) {
            queryWrapper.eq(TSysTaskWork.CONTROL_REASON, queryParam.getControlReason());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsElementChange())) {
            queryWrapper.eq(TSysTaskWork.IS_ELEMENT_CHANGE, queryParam.getIsElementChange());
        }
        if (StringHelper.isNotEmpty(queryParam.getChangeMeasure())) {
            queryWrapper.eq(TSysTaskWork.CHANGE_MEASURE, queryParam.getChangeMeasure());
        }
        if (StringHelper.isNotEmpty(queryParam.getUnitBelong())) {
            queryWrapper.eq(TSysTaskWork.UNIT_BELONG, queryParam.getUnitBelong());
        }
        if (StringHelper.isNotEmpty(queryParam.getCompanyId())) {
            queryWrapper.eq(TSysTaskWork.COMPANY_ID, queryParam.getCompanyId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSysTaskWork.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSysTaskWork.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSysTaskWork.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
