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

import com.github.pagehelper.Page;
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.PersonCompany;
import com.jpsoft.shinestar.modules.base.service.PersonCompanyService;
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("/personCompany")
@Api(description = "personCompany")
public class PersonCompanyController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonCompanyService personCompanyService;

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

        PersonCompany personCompany = new PersonCompany();

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

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

        try {
            personCompany.setId(UUID.randomUUID().toString());
            personCompany.setDelFlag(false);
            personCompany.setCreateBy(subject);
            personCompany.setCreateTime(new Date());
            
            int affectCount = personCompanyService.insert(personCompany);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personCompany);
            } 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("batchAdd")
    public MessageResult<Integer> batchAdd(@RequestBody String personId,
                                           @RequestBody List<String> companyIds,
                                           @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            MessageResult<List<PersonCompany>> list = list(personId,null,subject);
            for(PersonCompany personCompany : list.getData()){
                personCompanyService.delete(personCompany.getId());
            }

            for (String companyId : companyIds) {
                PersonCompany personCompany = new PersonCompany();

                personCompany.setId(UUID.randomUUID().toString());
                personCompany.setPersonId(Long.valueOf(personId));
                personCompany.setCompanyId(companyId);
                personCompany.setDelFlag(false);
                personCompany.setCreateBy(subject);
                personCompany.setCreateTime(new Date());

                personCompanyService.insert(personCompany);

                affectCount++;
            }

            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="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<PersonCompany> edit(@PathVariable("id") String id){
        MessageResult<PersonCompany> msgResult = new MessageResult<>();

        try {
            PersonCompany personCompany = personCompanyService.get(id);

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

        try {
            personCompany.setUpdateBy(subject);
            personCompany.setUpdateTime(new Date());
            
            int affectCount = personCompanyService.update(personCompany);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personCompany);
            } 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 {
            PersonCompany personCompany = personCompanyService.get(id);
            personCompany.setDelFlag(true);
            personCompany.setUpdateBy(subject);
            personCompany.setUpdateTime(new Date());

            int affectCount = personCompanyService.update(personCompany);

            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) {
                PersonCompany personCompany = personCompanyService.get(id);
                personCompany.setDelFlag(true);
                personCompany.setUpdateBy(subject);
                personCompany.setUpdateTime(new Date());

                affectCount += personCompanyService.update(personCompany);
            }

            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="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("id_","asc"));

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

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

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public MessageResult<List<PersonCompany>> list(
            @RequestParam(value="personId",defaultValue="") String personId,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestAttribute String subject){

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

        MessageResult<List<PersonCompany>> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();
        if (StringUtils.isNotEmpty(personId)) {
            searchParams.put("personId", personId);
        }
        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId", companyId);
        }
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("id_","asc"));

        Page<PersonCompany> page = personCompanyService.pageSearch(searchParams,1,1000,false,sortList);

        msgResult.setResult(true);
        msgResult.setData(page.getResult());

        return msgResult;
    }
}
