package com.lz.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingtalk.api.response.OapiCrmAuthGroupMemberListResponse;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.dao.DepartmentsDao;
import com.lz.modules.app.dto.ApprovalDto;
import com.lz.modules.app.dto.RecordDetailDto;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.enums.ResultRecordStatusEnum;
import com.lz.modules.app.enums.RoleEnums;
import com.lz.modules.app.model.TaskModel;
import com.lz.modules.app.resp.Step;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.dao.StaffRoleMapper;
import com.lz.modules.flow.entity.RecordAuth;
import com.lz.modules.flow.entity.StaffRole;
import com.lz.modules.flow.model.FlowModel;
import com.lz.modules.flow.service.RecordAuthService;
import com.lz.modules.flow.service.StaffRoleService;
import com.lz.modules.sys.dao.SysUserDao;
import com.lz.modules.sys.entity.SysUserEntity;
import com.lz.modules.sys.entity.app.ResultDetail;
import com.lz.modules.sys.entity.app.ResultRecord;
import com.lz.modules.sys.service.SysUserService;
import com.lz.modules.sys.service.app.ResultDetailService;
import com.lz.modules.sys.service.app.ResultRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.reactive.RxJava2CrudRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class TestController {

    @Autowired
    private ResultRecordService resultRecordService;

    @Autowired
    private DepartmentsService departmentsService;


    @Autowired
    private ResultDetailService resultDetailService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;
    @Autowired
    private StaffRoleService staffRoleService;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RecordAuthService recordAuthService;

    @RequestMapping("/test/xx")
    public void test(){
        ResultRecord resultRecord = new ResultRecord();
        resultRecord.setAllScore(new BigDecimal(10));
        resultRecord.setLastScore(new BigDecimal(8));
        resultRecord.setMonthTime(new Date());
        resultRecordService.insertResultRecord(resultRecord);
    }


    @RequestMapping("/test/department")
    public void department(){
        List<DepartmentsEntity> departmentsEntityList = departmentsService.selectEntityByParentDepartmentId("0");
        for(DepartmentsEntity child1:departmentsEntityList){
            child1.setLevel(1);
            departmentsService.updateById(child1);
            List<DepartmentsEntity> departmentsEntityList2 = departmentsService.selectEntityByParentDepartmentId(child1.getDepartmentId());
            for(DepartmentsEntity child2: departmentsEntityList2){
                child2.setLevel(2);
                departmentsService.updateById(child2);
                List<DepartmentsEntity> departmentsEntityList3 = departmentsService.selectEntityByParentDepartmentId(child2.getDepartmentId());
                for(DepartmentsEntity child3: departmentsEntityList3){
                    child3.setLevel(3);
                    departmentsService.updateById(child3);
                    List<DepartmentsEntity> departmentsEntityList4 = departmentsService.selectEntityByParentDepartmentId(child3.getDepartmentId());
                    for(DepartmentsEntity child4: departmentsEntityList4){
                        child4.setLevel(4);
                        departmentsService.updateById(child4);
                    }
                }
            }
        }
    }

    @RequestMapping("/test/relate")
    public void relate(){
        List<DepartmentsStaffRelateEntity> list = departmentsStaffRelateService.selectAll();
        for(DepartmentsStaffRelateEntity l:list){
            DepartmentsEntity departmentsEntity = departmentsService.selectByDepartmentId(l.getDepartmentId());
            l.setLevel(departmentsEntity.getLevel());
            departmentsStaffRelateService.updateById(l);
        }
    }

    /**
     * {
     *   "type": "node",
     *     "left": 818,
     *   "top": 510,
     *   "uuid": "id3",
     *   "prev": [
     *     "id1",
     *     "id2"
     *   ],
     *   "next": [
     *     "id4",
     *     "id5"
     *   ],
     *   "formData": {
     *     "stepName": "名称1",
     *     "ruleGroupList": [{
     *         "name": "名称2",
     *         "nextStep": "id5"
     *       },
     *       {
     *         "name": "名称6",
     *         "nextStep": "id7"
     *       }
     *     ]
     *   },
     *   "nextIfId": "id12",
     *   "nextElseId": "id11"
     * }
     */
    @RequestMapping("/test/step")
    public void step(){
        Long staffId = 294l;
        ResultRecord resultRecord = new ResultRecord();
        resultRecord.setType(2);
        resultRecord.setStaffId(staffId);
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(resultRecord.getStaffId());
        resultRecord.setDepartmentId(departmentsStaffRelateEntity.getDepartmentId());
        List<Step> test = resultDetailService.getStepList(resultRecord);
        List<String> list = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(test)){
            Step step = test.get(0);
            StaffEntity staffEntity = staffService.selectStaffById(staffId);
            if(staffEntity !=null && !staffEntity.getName().equals(step.getName())){
                list.add(staffEntity.getName());
            }
            for(Step s:test){
                list.add(s.getName());
            }
        }
        System.out.println(JSON.toJSONString(list));
        List<FlowModel> flowModels = new ArrayList<>();
        FlowModel flowModel = new FlowModel();

        for(String s:list){

        }
    }



    @RequestMapping("/test/userinfo")
    public void userinfo(){

    }


    @RequestMapping("/test/init")
    public void testinit(){
        List<String> allDeparmentIds = staffService.selectAllDeparmentIdsByDepartmentParentId("1");
        //获取部门下所有人员
        List<String> staffIds = staffService.staffsByAllDeparmentIds(allDeparmentIds);
        List<Object> collect=resultRecordService.listObjs(new QueryWrapper<ResultRecord>()
                .eq("is_delete",  0)
                .eq("type", 2)
                .like("month_time","2020-09")
                .in("department_id",allDeparmentIds)
                .in("staff_id",staffIds)
                .select(" DISTINCT staff_id"));
        List<String> collect1 = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(collect)){
            collect1 = collect.stream().map(o -> o.toString()).collect(Collectors.toList());
            System.out.println();
        }

    }



    // http://localhost:8080/lz_management/test/restore
    @RequestMapping("/test/restore")
    public void restore() throws Exception{
        List<StaffEntity> staffEntities = staffService.selectAll();
        for(StaffEntity staffEntity:staffEntities){
            //doRestore(staffEntity.getId());
        }
    }

    // http://localhost:8080/lz_management/test/doRestore?staffId=273
    @RequestMapping("/test/doRestore")
    public void doRestore(Long staffId) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StaffEntity staff = staffService.selectStaffById(staffId);
        List<ResultRecord> resultRecords = resultRecordService.selectResultRecordAllByStaffId(staffId);
        Date node = sdf.parse("2020-09-29 19:08:07");
        if(resultRecords== null || resultRecords.size() == 0){
            log.info("staffid = " + staffId + " ，没有数据");
            return;
        }
        boolean flag = true;
        for(ResultRecord resultRecord:resultRecords){
            if(resultRecord.getGmtCreate().getTime() > node.getTime()){
                List<ResultDetail> resultDetails = resultDetailService.selectByRecordIdAndType(resultRecord.getId(),1);
                if(resultDetails !=null && resultDetails.size() > 0){
                    flag = false;
                    log.info("staff_id " + staff.getId() + ",name = " + staff.getName()  + " ,己经正常");
                    return ;
                }
            }
        }
        if(flag){
            for(ResultRecord resultRecord:resultRecords){
                if(resultRecord.getGmtCreate().getTime() > node.getTime()){
                    resultRecord.setIsDelete(1);
                    log.info("staff_id " + staff.getId() + ",name = " + staff.getName()  + " ,删除不要数据");
                    resultRecordService.updateResultRecordById(resultRecord);
                }
            }
            for(int i = resultRecords.size() - 1 ;i >= 0 ; i --){
                ResultRecord resultRecord = resultRecords.get(i);
                if(resultRecord.getGmtCreate().getTime() < node.getTime()){
                    List<ResultDetail> resultDetails = resultDetailService.selectByRecordIdAndType(resultRecord.getId(),1);
                    if(resultDetails !=null && resultDetails.size() > 0){
                        resultRecord.setIsDelete(0);
                        log.info("staff_id " + staff.getId() + ",name = " + staff.getName()  + " ,数据恢复");
                        resultRecordService.updateResultRecordById(resultRecord);
                        break;
                    }
                }
            }
        }
    }

    // http://localhost:8080/lz_management/test/resultrecord?resultRecordId=475
    @RequestMapping("/test/resultrecord")
    public void resultRecorcd(Long resultRecordId) throws Exception{
        R r = resultRecordService.initFlowRecord(resultRecordId);
    }

    // http://localhost:8080/lz_management/test/getAuth?userId=298
    @RequestMapping("/test/getAuth")
    public R getAuth(Long userId) throws Exception{
        Map<String,Integer> map = staffRoleService.getRoleByUserId(userId);
        return R.ok().put("data",map);
    }

    @Autowired
    private StaffRoleMapper staffRoleMapper;

    // http://localhost:8080/lz_management/test/testmaster
    @RequestMapping("/test/testmaster")
    public R testmaster(Long userId) throws Exception{
        List<StaffRole> masterPMs = staffRoleMapper.selectStaffRolesByDepartmentLevelList(Arrays.asList(new String[]{RoleEnums.MASTER_PM.getName()}));


        return R.ok();
    }


    public static void main(String[] args) {
        String a = "{\"313\":[17,20,13]}";
        Map<String,Object> map = JSONObject.parseObject(a,Map.class);
        List<Long> roleIds = null;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(entry.getValue() !=null ){
               roleIds = JSON.parseArray(entry.getValue().toString(),Long.class);
            }
        }
        System.out.println(roleIds);
    }

    //http://localhost:8080/lz_management/test/reset/data?resultRecordId=3682
    @RequestMapping("/test/reset/data")
    public R getResetData(RecordDetailDto recordDetailDto) {
        return resultRecordService.getResetData(recordDetailDto);
    }


    // 重置：http://localhost:8080/lz_management/test/approval?resultRecordId=3702&status=9&menuName=cccc&flowRecordId=33987&resetFlag=0
    @RequestMapping("/test/approval")
    public R approval(ApprovalDto approvalDto) {
        try {
            return resultRecordService.newApproval(approvalDto);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }


    // http://localhost:8080/lz_management/test/task/comment?taskId=1&content=xxx&staffId=294&atStaffIds=314,320
    @RequestMapping("/test/task/comment")
    public R taskComment(TaskModel taskModel) {
        return staffRoleService.taskComment(taskModel);
    }


    //http://localhost:8080/lz_management/test/comment/list?detailId=4917&pageSize=2
    @RequestMapping("/test/comment/list")
    public R commentList(TaskModel taskModel) {
        return staffRoleService.commentList(taskModel);
    }
}
