package com.ruoyi.web.controller.grid;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridPendingPeopleExt;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.system.ISysUserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author : peter
 * @description: TODO
 * @date : 2022-05-04 16:07
 */
@Api(tags = "网格管理 - 待认领人口管理")
@RestController
@RequestMapping("/api/grid/pendingPeople")
public class PendingPeopleController {

    @Autowired
    private GridPendingPeopleService gridPendingPeopleService;
    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridRegionService gridRegionService;
    @Autowired
    private GridWgLogService gridWgLogService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 待认领人口信息列表
     */
    @GetMapping(value = "/list")
    public AjaxResult list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                           @RequestParam(value = "wgCode") String wgCode,
                           @RequestParam(value = "level") String level,
                           @RequestParam(value = "value", required = false) String value) {
        try {
            GridPendingPeopleExample ex = new GridPendingPeopleExample();
            GridPendingPeopleExample.Criteria ca = ex.createCriteria();
            GridPendingPeopleExample.Criteria ca1 = ex.createCriteria();
            ca.andStatusEqualTo("0");
            ca1.andStatusEqualTo("0");
            if ("3".equals(level)) {
                GridRegionExample example = new GridRegionExample();
                GridRegionExample.Criteria criteria = example.createCriteria();
                criteria.andIsValidEqualTo("1");
                criteria.andWgCodeEqualTo(wgCode);
                criteria.andLevelEqualTo("3");
                GridRegion bs = gridRegionService.selectFirstByExample(example);
                if (bs != null) {
                    wgCode = bs.getWgParentId();
                }
            }
            if (StringUtils.isNotBlank(wgCode)) {
                ca.andWgCodeLike(wgCode + "%");
                ca1.andWgCodeLike(wgCode + "%");
            }

            if (StringUtils.isNotBlank(value)) {
                ca.andPersonNameLike("%" + value + "%");
                ca1.andIdCardLike("%" + value + "%");
            }
            ex.or(ca1);
            ex.setOrderByClause(" create_time desc, person_name");
            PageHelper.startPage(pageNum, pageSize);
            List<GridPendingPeople> peopleList = gridPendingPeopleService.selectByExample(ex);

            List<GridPendingPeopleExt> peopleExtList = BeanCopyUtil.bathToBean(peopleList, GridPendingPeopleExt.class);

            for (GridPendingPeopleExt p : peopleExtList) {
                gridPendingPeopleService.selectGridPendingPeopleExt(p);
            }
            PageInfo<GridPendingPeopleExt> pageInfo = ZQTPageUtil.build(peopleList, peopleExtList);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    /**
     * 微信上人口注册
     */
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody GridPendingPeople wsPendingPeople) {
        Validator.validateNotEmpty(wsPendingPeople.getIdCard(), "身份证号不能为空");
        Validator.validateNotEmpty(wsPendingPeople.getPhone(), "手机号为不能空");
        String ID_18 = wsPendingPeople.getIdCard();
        boolean valid = IdcardUtil.isValidCard(ID_18);
        if (!valid) {
            return AjaxResult.error(400, "该人员身份证信息不合法");
        }
        GridPendingPeopleExample ex = new GridPendingPeopleExample();
        GridPendingPeopleExample.Criteria ca = ex.createCriteria();
        ca.andStatusEqualTo("1");
        ca.andIdCardEqualTo(wsPendingPeople.getIdCard());
        int count = gridPendingPeopleService.countByExample(ex);
        if (count > 0) {
            return AjaxResult.error(400, "该人员身份证信息已经登记");
        }
        GridPendingPeopleExample ex1 = new GridPendingPeopleExample();
        GridPendingPeopleExample.Criteria ca1 = ex1.createCriteria();
        ca1.andStatusEqualTo("1");
        ca1.andPhoneEqualTo(wsPendingPeople.getPhone());
        int count1 = gridPendingPeopleService.countByExample(ex1);
        if (count1 > 0) {
            return AjaxResult.error(400, "该人员手机号码已经登记");
        }
        wsPendingPeople.setBirthday(IdcardUtil.getYearByIdCard(ID_18) + "-" + IdcardUtil.getMonthByIdCard(ID_18) + "-" + IdcardUtil.getDayByIdCard(ID_18));
        if (StringUtils.isBlank(wsPendingPeople.getSex())) {
            wsPendingPeople.setSex(IdcardUtil.getGenderByIdCard(ID_18) == 1 ? "男" : "女");
        }
        if (StringUtils.isNotBlank(wsPendingPeople.getId())) {
            wsPendingPeople.setStatus("0");
            wsPendingPeople.setUpdateTime(DateUtil.formatDateTime(new Date()));
            gridPendingPeopleService.updateByPrimaryKeySelective(wsPendingPeople);
        } else {
            wsPendingPeople.setId(IdUtil.fastSimpleUUID());
            wsPendingPeople.setCreateTime(DateUtil.formatDateTime(new Date()));
            wsPendingPeople.setStatus("0");
            gridPendingPeopleService.insertSelective(wsPendingPeople);
        }
        // 发送消息
        gridPendingPeopleService.sendMessage(wsPendingPeople.getPersonName(), wsPendingPeople.getWgCode());
        return AjaxResult.success(null);
    }

    /**
     * 待认领人口认领
     */
    @GetMapping(value = "/agree")
    public AjaxResult agree(@RequestParam(value = "id") String id,
                            @RequestParam(value = "wgCode") String wgCode,
                            @RequestParam(value = "createId") String createId,
                            @RequestParam(value = "rklxCode", required = false) String rklxCode,
                            @RequestParam(value = "rkbqCode", required = false) String rkbqCode) {
        GridPendingPeople wsPendingPeople = gridPendingPeopleService.selectByPrimaryKey(id);
        GridPeopleExample ex = new GridPeopleExample();
        GridPeopleExample.Criteria ca = ex.createCriteria();
        ca.andIdCardEqualTo(wsPendingPeople.getIdCard());
        ca.andIsValidEqualTo(Byte.valueOf("1"));
        int count = gridPeopleService.countByExample(ex);
        if (count > 0) {
            return AjaxResult.error(400, "该人员身份证信息已在人口信息库中");
        }
        GridPeopleExample ex1 = new GridPeopleExample();
        GridPeopleExample.Criteria ca1 = ex1.createCriteria();
        ca1.andPhoneEqualTo(wsPendingPeople.getPhone());
        ca1.andIsValidEqualTo(Byte.valueOf("1"));
        int count1 = gridPeopleService.countByExample(ex1);
        if (count1 > 0) {
            return AjaxResult.error(400, "该人员手机号码已在人口信息库中");
        }
        GridPeople wsPeople = BeanCopyUtil.toBean(wsPendingPeople, GridPeople.class);
        wsPeople.setId(IdUtil.fastSimpleUUID());
        wsPeople.setCreateTime(DateUtil.formatDateTime(new Date()));
        wsPeople.setWgCode(wgCode);
        wsPeople.setCreateId(createId);
        wsPeople.setRklxCode(rklxCode);
        wsPeople.setRkbqCode(rkbqCode);
        gridPeopleService.insertSelective(wsPeople);
        wsPendingPeople.setStatus("1");
        gridPendingPeopleService.updateByPrimaryKeySelective(wsPendingPeople);

        // 日志
        GridWgLog wsWgLog = new GridWgLog();
        wsWgLog.setCreateId(createId);
        SysUser sysUser = sysUserService.selectUserById(createId);
        wsWgLog.setCreateName(sysUser != null ? sysUser.getNickName() : "");
        wsWgLog.setCreateWgCode(wsPeople.getWgCode());
        wsWgLog.setObjectName(wsPeople.getPersonName());
        wsWgLog.setType("1");
        wsWgLog.setOperate("insert");
        wsWgLog.setObjectId(wsPeople.getId());
        gridWgLogService.add(wsWgLog);

        return AjaxResult.success(null);
    }

    /**
     * 查无此人
     */
    @GetMapping(value = "/reject")
    public AjaxResult reject(@RequestParam(value = "id") String id,
                             @RequestParam(value = "createId") String createId) {
        GridPendingPeople wsPendingPeople = gridPendingPeopleService.selectByPrimaryKey(id);
        wsPendingPeople.setStatus("2");
        wsPendingPeople.setCreateId(createId);
        gridPendingPeopleService.updateByPrimaryKeySelective(wsPendingPeople);
        return AjaxResult.success(null);
    }

    /**
     * 详情
     */
    @GetMapping(value = "/detail/{id}")
    public AjaxResult detail(@PathVariable("id") String id) {
        GridPendingPeople wsPendingPeople = gridPendingPeopleService.selectByPrimaryKey(id);
        GridPendingPeopleExt wsPendingPeopleExt = BeanCopyUtil.toBean(wsPendingPeople, GridPendingPeopleExt.class);
        if (wsPendingPeopleExt != null) {
            gridPendingPeopleService.selectGridPendingPeopleExt(wsPendingPeopleExt);
        }
        return AjaxResult.success(wsPendingPeopleExt);
    }

    /**
     * 详情
     */
    @GetMapping(value = "/detail")
    public AjaxResult detailPhone(@RequestParam(value = "phone") String phone) {
        GridPendingPeopleExample ex = new GridPendingPeopleExample();
        GridPendingPeopleExample.Criteria ca = ex.createCriteria();
        ca.andPhoneEqualTo(phone);
        GridPendingPeople wsPendingPeople = gridPendingPeopleService.selectFirstByExample(ex);
        GridPendingPeopleExt wsPendingPeopleExt = BeanCopyUtil.toBean(wsPendingPeople, GridPendingPeopleExt.class);
        if (wsPendingPeopleExt != null) {
            gridPendingPeopleService.selectGridPendingPeopleExt(wsPendingPeopleExt);
        }
        return AjaxResult.success(wsPendingPeopleExt);
    }
}
