package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonApplicationInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonApplicationInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/base/personApplication")
@Api(description = "personApplication")
public class PersonApplicationController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonApplicationInfoService personApplicationInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<PersonApplicationInfo> create(){
        MessageResult<PersonApplicationInfo> msgResult = new MessageResult<>();

        PersonApplicationInfo personApplicationInfo = new PersonApplicationInfo();

        msgResult.setData(personApplicationInfo);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<PersonApplicationInfo> add(@RequestBody PersonApplicationInfo personApplicationInfo, @RequestAttribute String subject){
        MessageResult<PersonApplicationInfo> msgResult = new MessageResult<>();

        try {
            personApplicationInfo.setId(UUID.randomUUID().toString());
            personApplicationInfo.setDelFlag(false);
            personApplicationInfo.setCreateBy(subject);
            personApplicationInfo.setCreateTime(new Date());

            int affectCount = personApplicationInfoService.insert(personApplicationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personApplicationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<PersonApplicationInfo> edit(@PathVariable("id") String id){
        MessageResult<PersonApplicationInfo> msgResult = new MessageResult<>();

        try {
            PersonApplicationInfo personApplicationInfo = personApplicationInfoService.get(id);

            if (personApplicationInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(personApplicationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<PersonApplicationInfo> update(@RequestBody PersonApplicationInfo personApplicationInfo,@RequestAttribute String subject){
        MessageResult<PersonApplicationInfo> msgResult = new MessageResult<>();

        try {
            personApplicationInfo.setUpdateBy(subject);
            personApplicationInfo.setUpdateTime(new Date());

            int affectCount = personApplicationInfoService.update(personApplicationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personApplicationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            PersonApplicationInfo personApplicationInfo = personApplicationInfoService.get(id);
            personApplicationInfo.setDelFlag(true);
            personApplicationInfo.setUpdateBy(subject);
            personApplicationInfo.setUpdateTime(new Date());

            int affectCount = personApplicationInfoService.update(personApplicationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList, @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                PersonApplicationInfo personApplicationInfo = personApplicationInfoService.get(id);
                personApplicationInfo.setDelFlag(true);
                personApplicationInfo.setUpdateBy(subject);
                personApplicationInfo.setUpdateTime(new Date());

                affectCount += personApplicationInfoService.update(personApplicationInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String name,String telephone,String status,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        //当前用户ID
        User user = userService.get(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));

        if (StringUtils.isNotEmpty(name)) {
            searchParams.put("name","%" + name + "%");
        }

        if(!userService.hasRole(user.getId(),"SYSADMIN")) {
            //非系统管理员只能查看自己单位下的设备
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            searchParams.put("companyCode", companyInfo.getCode() + "%");
        }

        if (StringUtils.isNotEmpty(telephone)) {
            searchParams.put("telephone",telephone);
        }
        if (StringUtils.isNotEmpty(status)) {
            searchParams.put("status",status);
        }

        Page<PersonApplicationInfo> page = personApplicationInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="审批")
    @RequestMapping(value = "statusCheck",method = RequestMethod.POST)
    public MessageResult<Integer> statusCheck(String id,String status,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            //当前用户ID
            User user = userService.get(subject);

            PersonApplicationInfo personApplicationInfo = personApplicationInfoService.get(id);

            personApplicationInfoService.examineApplicationPerson(null,user,id,status,null,personApplicationInfo.getCompanyId());

            msgResult.setResult(true);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

}
