package com.ghy.web.controller.worker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.enums.GoodsStatus;
import com.ghy.common.enums.WorkerStatus;
import com.ghy.common.enums.WorkerType;
import com.ghy.common.utils.CacheUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.goods.domain.Goods;
import com.ghy.goods.domain.GoodsCategory;
import com.ghy.goods.service.GoodsCategoryService;
import com.ghy.goods.service.GoodsService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.web.pojo.vo.WorkerListRequest;
import com.ghy.web.pojo.vo.WorkerListResponse;
import com.ghy.web.pojo.vo.WorkerSettledRequest;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerArea;
import com.ghy.worker.domain.WorkerBank;
import com.ghy.worker.domain.WorkerGoodsCategory;
import com.ghy.worker.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author clunt
 * 师傅端Controller
 */
@Controller
@RequestMapping("/worker")
public class WorkerController extends BaseController {

    private String prefix = "worker";

    @Autowired
    private WorkerService workerService;

    @Autowired
    private WorkerAreaService workerAreaService;

    @Autowired
    private WorkerGoodsCategoryService workerGoodsCategoryService;

    @Autowired
    private WorkerSpecialSkillService specialSkillService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private WorkerBankService workerBankService;

    @Autowired
    private ISysAreaService sysAreaService;

    @RequiresPermissions("worker:worker:view")
    @GetMapping()
    public String worker(){
        return prefix + "/worker";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody Worker worker){
        try {
            Assert.notNull(worker.getPhone(), "手机号码为空");
            List<Worker> workerList = workerService.getWorkByPhoneAndPwd(worker);
            if(workerList.size() > 0){
                return AjaxResult.success(workerList.get(0));
            }else {
                return AjaxResult.error("用户名或密码错误!");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error("登陆失败!");
        }
    }

    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(@RequestBody Worker request){
        try {
            if (CacheUtils.get(request.getPhone()) == null){
                return AjaxResult.error("验证码无效!");
            }
            // 验证码校验正确
            if(CacheUtils.get(request.getPhone()).toString().equals(request.getRegisterCode())){
                int result = workerService.updateWorker(request);
                if(result > 0){
                    CacheUtils.remove(request.getPhone());
                    return AjaxResult.success("注册成功!");
                }else {
                    return AjaxResult.error("注册失败!");
                }
            }else {
                return AjaxResult.error("验证码错误!");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

//    @RequiresPermissions("worker:worker:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkerListRequest workerListRequest)
    {
        List<WorkerListResponse> resList = new ArrayList<WorkerListResponse>();

        try {
            // 查询满足区域条件的师傅区域记录
            WorkerArea workerArea = new WorkerArea();
            workerArea.setDistrictId(workerListRequest.getAreaId());
            List<WorkerArea> workerAreaList = workerAreaService.getWorkerAreaList(workerArea);
            List<Long> workerIdsByArea = workerAreaList.stream().map(WorkerArea::getWorkerId).collect(Collectors.toList());
            // 查询满足技能条件的师傅技能记录
            WorkerGoodsCategory workerGoodsCategory = new WorkerGoodsCategory();
            workerGoodsCategory.setGoodsCategoryId(workerListRequest.getGoodsCategoryId());
            List<WorkerGoodsCategory> workerGoodsCategoryList = workerGoodsCategoryService.getWorkerGoodsCategory(workerGoodsCategory);
            List<Long> workerIdsByCategory = workerGoodsCategoryList.stream().map(WorkerGoodsCategory::getWorkerId).collect(Collectors.toList());
            // 两个list中的workerid取交集
            List<Long> resWorkerIds = new ArrayList<>(CollectionUtils.intersection(workerIdsByArea, workerIdsByCategory));

            if (CollectionUtils.isEmpty(resWorkerIds)) {
                // 交集不存在的情况直接返回空list
                return getDataTable(resList);
            }

            startPage();
            Worker worker = new Worker();
            worker.setWorkerIds(CollectionUtils.isNotEmpty(resWorkerIds) ? resWorkerIds : null);
            worker.setName(workerListRequest.getWorkerName());
            if(this.getSysUser().getDept().getParentId() != 101){
                worker.setDeptId(this.getSysUser().getDept().getParentId());
            }
            List<Worker> list = workerService.getWorkList(worker);
            TableDataInfo dataTable = getDataTable(list);
            list.forEach(w -> {
                Goods goods = new Goods();
                goods.setWorkerId(w.getWorkerId());
                goods.setStatus(Integer.valueOf(GoodsStatus.OK.getCode()));
                WorkerListResponse workerListResponse = JSONObject.parseObject(JSON.toJSONString(w), WorkerListResponse.class);
                workerListResponse.setGoodsList(goodsService.selectGoodsList(goods));
                workerListResponse.setWorkerAreas(workerAreaService.getByWorker(w.getWorkerId()));
                workerListResponse.setGoodsCategories(workerGoodsCategoryService.getByWorker(w.getWorkerId()));
                workerListResponse.setSpecialSkills(specialSkillService.getByWorker(w.getWorkerId()));
                resList.add(workerListResponse);

            });
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(0);
            rspData.setRows(resList);
            rspData.setTotal(dataTable.getTotal());
            return rspData;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return getDataTable(new ArrayList<>());
        }
    }

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody WorkerListRequest workerListRequest)
    {
        List<WorkerListResponse> resList = new ArrayList<WorkerListResponse>();
        // 查询参数
        Worker worker = new Worker();

        try {
            // 查询满足区域条件的师傅区域记录
            worker.setDistrictId(workerListRequest.getAreaId());
            worker.setDistrictIds(workerListRequest.getAreaIds());
            // 查询需要排除的区
            if (workerListRequest.getExceptParentAreaId() != null) {
                SysArea areaParams = new SysArea();
                areaParams.setParentCode(workerListRequest.getExceptParentAreaId().toString());
                List<SysArea> exceptAreaList = sysAreaService.selectSysAreaList(areaParams);
                List<Long> exceptAreaIds = exceptAreaList.stream().map(SysArea::getAreaId).collect(Collectors.toList());
                worker.setExceptDistrictIds(exceptAreaIds);
            }
//            WorkerArea workerArea = new WorkerArea();
//            workerArea.setDistrictId(workerListRequest.getAreaId());
//            List<WorkerArea> workerAreaList = workerAreaService.getWorkerAreaList(workerArea);
//            List<Long> workerIdsByArea = workerAreaList.stream().map(WorkerArea::getWorkerId).collect(Collectors.toList());
            // 查询满足技能条件的师傅技能记录
//            WorkerGoodsCategory workerGoodsCategory = new WorkerGoodsCategory();
            // 判断类目id是否为第三级，不是的话需要找到所有符合条件的第三级类目id作为新的条件
            if (workerListRequest.getGoodsCategoryId() != null) {
                GoodsCategory goodsCategory = goodsCategoryService.selectById(workerListRequest.getGoodsCategoryId());
                if (goodsCategory.getLevel() == 0) {
                    worker.setGoodsCategoryId(null);
                } else if (goodsCategory.getLevel() == 1) {
                    GoodsCategory params = new GoodsCategory();
                    params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                    List<GoodsCategory> secondCategories = goodsCategoryService.selectGoodsCategoryList(params);
                    List<Long> secondCategoryIds = secondCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                    List<Long> thirdCategoryIds = new ArrayList<Long>();
                    secondCategoryIds.forEach(id -> {
                        params.setParentCategoryId(id);
                        List<GoodsCategory> thirdCategories = goodsCategoryService.selectGoodsCategoryList(params);
                        thirdCategoryIds.addAll(thirdCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList()));
                    });
                    worker.setGoodsCategoryId(null);
                    worker.setGoodsCategoryIds(thirdCategoryIds);
                } else if (goodsCategory.getLevel() == 2) {
                    GoodsCategory params = new GoodsCategory();
                    params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                    List<GoodsCategory> filteredCategory = goodsCategoryService.selectGoodsCategoryList(params);
                    List<Long> filteredCategoryIds = filteredCategory.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                    worker.setGoodsCategoryId(null);
                    worker.setGoodsCategoryIds(filteredCategoryIds);
                } else {
                    worker.setGoodsCategoryId(workerListRequest.getGoodsCategoryId());
                }
            }
//            List<WorkerGoodsCategory> workerGoodsCategoryList = workerGoodsCategoryService.getWorkerGoodsCategory(workerGoodsCategory);
//            List<Long> workerIdsByCategory = workerGoodsCategoryList.stream().map(WorkerGoodsCategory::getWorkerId).collect(Collectors.toList());
            // 两个list中的workerid取交集
//            List<Long> resWorkerIds = new ArrayList<>(CollectionUtils.intersection(workerIdsByArea, workerIdsByCategory));

//            if (CollectionUtils.isEmpty(resWorkerIds)) {
//                // 交集不存在的情况直接返回空list
//                return getDataTable(resList);
//            }

            startPage();
//            worker.setWorkerIds(CollectionUtils.isNotEmpty(resWorkerIds) ? resWorkerIds : null);
            worker.setName(workerListRequest.getWorkerName());
            List<Worker> list = workerService.getWorkList(worker);
            list.forEach(w -> {
                Goods goods = new Goods();
                goods.setWorkerId(w.getWorkerId());
                goods.setStatus(Integer.valueOf(GoodsStatus.OK.getCode()));
                WorkerListResponse workerListResponse = JSONObject.parseObject(JSON.toJSONString(w), WorkerListResponse.class);
                workerListResponse.setGoodsList(goodsService.selectGoodsList(goods));
                if (workerListRequest.isJustShowCurWorkerArea()) {
                    workerListResponse.setWorkerAreas(workerAreaService.getWorkerAreaList(new WorkerArea(){{
                        setWorkerId(w.getWorkerId());
                        setDistrictId(worker.getDistrictId());
                        setDistrictIds(worker.getDistrictIds());
                    }}));
                } else {
                    workerListResponse.setWorkerAreas(workerAreaService.getByWorker(w.getWorkerId()));
                }
                workerListResponse.setGoodsCategories(workerGoodsCategoryService.getByWorker(w.getWorkerId()));
                workerListResponse.setSpecialSkills(specialSkillService.getByWorker(w.getWorkerId()));
                resList.add(workerListResponse);
            });
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
        }

        return getDataTable(resList);
    }

    @PostMapping("/getDetailById")
    @ResponseBody
    public AjaxResult getDetailById(@RequestBody WorkerListRequest workerListRequest)
    {
        WorkerListResponse workerListResponse = new WorkerListResponse();

        try {
            Assert.notNull(workerListRequest.getWorkerId(), "Worker id can not be null");

            Worker worker = workerService.selectById(workerListRequest.getWorkerId());
            Goods goods = new Goods();
            goods.setWorkerId(workerListRequest.getWorkerId());
            goods.setStatus(Integer.valueOf(GoodsStatus.OK.getCode()));
            workerListResponse = JSONObject.parseObject(JSON.toJSONString(worker), WorkerListResponse.class);
            workerListResponse.setGoodsList(goodsService.selectGoodsList(goods));
            workerListResponse.setWorkerAreas(workerAreaService.getByWorker(worker.getWorkerId()));
            workerListResponse.setGoodsCategories(workerGoodsCategoryService.getByWorker(worker.getWorkerId()));
            workerListResponse.setSpecialSkills(specialSkillService.getByWorker(worker.getWorkerId()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(workerListResponse);
    }

    @PostMapping("/update")
    @ResponseBody
    public AjaxResult updateWorker(@RequestBody Worker worker){
        try {
            workerService.updateWorker(worker);
            return AjaxResult.success("修改成功");
        }catch (Exception e){
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Worker worker){
        try {
            workerService.updateWorker(worker);
            return AjaxResult.success("修改成功");
        }catch (Exception e){
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/settled")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public  AjaxResult settled(@RequestBody WorkerSettledRequest request) {
        // 入驻区域信息持久化
        workerAreaService.updateWorkerServArea(request.getWorkerId(), request.getWorkerAreas());
        // 入驻服务品类信息持久化
        workerGoodsCategoryService.updateWorkerGoodsCategory(request.getWorkerId(), request.getGoodsCategories());
        // 更新师傅入驻类型为服务商
        Worker worker = new Worker();
        worker.setWorkerId(request.getWorkerId());
        worker.setType(WorkerType.SP.getCode());
        workerService.updateWorker(worker);
        return AjaxResult.success("保存成功");
    }
}
