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

import com.alipay.api.domain.Person;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleIconService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
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 javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户角色绑定
 * sz
 * **/
@RestController
@RequestMapping("/base/personPopedom")
@Api(description = "personPopedom")
public class PersonPopedomController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonPopedomService personPopedomService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private PersonRoleIconService personRoleIconService;

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

        PersonPopedom personPopedom = new PersonPopedom();

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

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

        try {

            PersonPopedom pp = personPopedomService.findByVerify(personPopedom);
            if(pp != null){
                throw new Exception("已存在该角色");
            }

            personPopedom.setId(UUID.randomUUID().toString());
            personPopedom.setDelFlag(false);
            personPopedom.setCreateBy(subject);
            personPopedom.setCreateTime(new Date());

            //保存默认的7个图标
            String showIcon = personRoleIconService.getDefaultIcon(personPopedom.getPersonRoleId());
            personPopedom.setShowIconId(showIcon);
            
            int affectCount = personPopedomService.insert(personPopedom);

            if (affectCount > 0) {
                PersonInfo pi = personInfoService.get(personPopedom.getPersonId());
                if(pi != null){
                    //如果默认为空,则添加默认
                    if(StringUtils.isEmpty(pi.getCompanyId()) || StringUtils.isEmpty(pi.getPopedom())){
                        pi.setCompanyId(personPopedom.getCompanyId());
                        pi.setPopedom(personPopedom.getId());
                        pi.setUpdateBy(subject);
                        pi.setUpdateTime(new Date());
                        personInfoService.update(pi);
                    }
                }
                msgResult.setResult(true);
                msgResult.setData(personPopedom);
            } 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<PersonPopedom> edit(@PathVariable("id") String id){
        MessageResult<PersonPopedom> msgResult = new MessageResult<>();

        try {
            PersonPopedom personPopedom = personPopedomService.get(id);

            if (personPopedom != null) {
                msgResult.setResult(true);
                msgResult.setData(personPopedom);
            } 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<PersonPopedom> update(@RequestBody PersonPopedom personPopedom,@RequestAttribute String subject){
        MessageResult<PersonPopedom> msgResult = new MessageResult<>();

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

            PersonPopedom pp = personPopedomService.findByVerify(personPopedom);

            if(pp != null && !pp.getId().equals(personPopedom.getId())){
                throw new Exception("已存在该角色");
            }

            int affectCount = personPopedomService.update(personPopedom);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personPopedom);
            } 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 {
            PersonPopedom personPopedom = personPopedomService.get(id);

            int ppCount = personPopedomService.countByPerson(personPopedom.getPersonId());
            if(ppCount > 1) {
                personPopedom.setDelFlag(true);
                personPopedom.setUpdateBy(subject);
                personPopedom.setUpdateTime(new Date());
                int affectCount = personPopedomService.update(personPopedom);
                if (affectCount > 0) {
                    PersonInfo pi = personInfoService.get(personPopedom.getPersonId());
                    //判断是否删除的是用户默认角色
                    if(personPopedom.getId().equals(pi.getPopedom())){
                        //是 修改用户默认
                        PersonPopedom newPp = personPopedomService.findOneByPersonId(personPopedom.getPersonId());
                        pi.setCompanyId(newPp.getCompanyId());
                        pi.setPopedom(newPp.getId());
                        pi.setUpdateBy(subject);
                        pi.setUpdateTime(new Date());
                        personInfoService.update(pi);
                    }

                    msgResult.setResult(true);
                    msgResult.setData(affectCount);
                } else {
                    msgResult.setResult(false);
                    msgResult.setMessage("删除失败");
                }
            }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) {
                PersonPopedom personPopedom = personPopedomService.get(id);
                personPopedom.setDelFlag(true);
                personPopedom.setUpdateBy(subject);
                personPopedom.setUpdateTime(new Date());

                affectCount += personPopedomService.update(personPopedom);
            }

            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 id,
            @RequestParam(value="personId",defaultValue="") String personId,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="personRoleId",defaultValue="") String personRoleId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("b.sort_no","asc"));
        sortList.add(new Sort("a.create_time","asc"));

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

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

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

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

        Page<PersonPopedom> page = personPopedomService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        PersonInfo pi = personInfoService.get(Long.valueOf(personId));
        for(PersonPopedom pp : page.getResult()){
            if(pp.getPopularizePersonId() != null) {
                PersonInfo popularizePerson = personInfoService.get(pp.getPopularizePersonId());
                if(popularizePerson != null) {
                    pp.setPopularizePersonName(popularizePerson.getName());
                }
            }

            if(pp.getId().equals(pi.getPopedom())){
                pp.setIsDefault(true);
                break;
            }
        }

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

        return msgResult;
    }

    @ApiOperation(value = "修改默认公司角色")
    @PostMapping("changeDefault")
    public MessageResult<Integer> changeDefault(String id, String personId, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;
            PersonPopedom pp =  personPopedomService.get(id);
            PersonInfo pi = personInfoService.get(Long.valueOf(personId));
            pi.setCompanyId(pp.getCompanyId());
            pi.setPopedom(pp.getId());
            pi.setUpdateBy(subject);
            pi.setUpdateTime(new Date());
            affectCount = personInfoService.update(pi);

            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;
    }
}
