package cn.gtmap.estateplat.config.web.qlxx;/* 
 * @author <a href="mailto:lizhi@gtmap.cn">lizhi</a>
 * @version 1.0, 2017/8/30
 * @description
 */

import cn.gtmap.estateplat.config.core.service.*;
import cn.gtmap.estateplat.config.service.ManageCertificateService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.IDValidator;
import cn.gtmap.estateplat.config.utils.ReadXmlProps;
import cn.gtmap.estateplat.config.web.main.BaseController;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.core.support.mybatis.page.model.Page;
import cn.gtmap.estateplat.core.support.mybatis.page.repository.Repo;
import cn.gtmap.estateplat.model.server.core.*;
import cn.gtmap.estateplat.utils.CommonUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gtis.common.util.UUIDGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bdcQlrxx")
public class BdcQlrxxController extends BaseController {
    @Autowired
    private Repo repository;
    @Autowired
    private BdcQlrService bdcQlrService;
    @Autowired
    private BdcZdGlService bdcZdGlService;
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private BdcZsService bdcZsService;
    @Autowired
    private LogService logService;
    @Autowired
    private BdcXmService bdcXmService;
    @Autowired
    private DataManagerService dataManagerService;
    @Autowired
    private QllxService qllxService;
    @Autowired
    private ManageCertificateService manageCertificateService;

    @RequestMapping("")
    public String index(Model model, String proid, String djId, String bdcdyh, String bdclx, String qllx, String bdcdyFwlx, String noPropertyRight) {
        if (StringUtils.isNotBlank(proid)) {
            model.addAttribute("proid", proid);
            BdcXm bdcXm = bdcXmService.getBdcXmByProid(proid);
            model.addAttribute("sqfbcz", bdcXm.getSqfbcz());
        }
        List<BdcZdZjlx> bdcZdZjlxList = bdcZdGlService.getBdcZdZjlxList();
        model.addAttribute("bdcZdZjlxList", bdcZdZjlxList);
        model.addAttribute("qllx", qllx);
        model.addAttribute("djId", djId);
        model.addAttribute("bdcdyh", bdcdyh);
        model.addAttribute("bdclx", bdclx);
        model.addAttribute("bdcdyFwlx", bdcdyFwlx);
        model.addAttribute("noPropertyRight", noPropertyRight);
        model.addAttribute("bdcZdZjlxListJson", JSON.toJSONString(bdcZdZjlxList));
        List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(proid);
        model.addAttribute("bdcQlrList", bdcQlrList);
        model.addAttribute("bdcYwrList", bdcQlrService.queryBdcYwrByProid(proid));
        model.addAttribute("gyfsList", bdcZdGlService.getZdGyfs());
        if (CollectionUtils.isNotEmpty(bdcQlrList)) {
            model.addAttribute("gyfs", bdcQlrList.get(0).getGyfs());
        }
        return "qlxx/bdcQlr";
    }

    @ResponseBody
    @RequestMapping("/getQlrPagesJson")
    public Object getQlrPagesJson(Pageable pageable, String qlrmc, String qlrzjh, String proid) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Page<HashMap> dataPaging = null;
        if (StringUtils.isNotBlank(proid)) {
            map.put("proid", proid);
            if (StringUtils.isNotBlank(qlrmc))
                map.put("qlrmc", qlrmc);
            if (StringUtils.isNotBlank(qlrzjh))
                map.put("qlrzjh", qlrzjh);
            dataPaging = repository.selectPaging("getQlrListByPage", map, pageable);
        }
        return dataPaging;
    }

    @ResponseBody
    @RequestMapping("/delQlr")
    public Map<String, String> delQlr(Model model, String qlrid, String proid, String sqfbcz) {
        Map<String, String> map = Maps.newHashMap();
        String result = "success";
        if (StringUtils.isNoneBlank(proid, qlrid)) {
            try {
                if (StringUtils.equals(sqfbcz, Constants.FLAG_YES_CHINESE)) {
                    Example example = new Example(BdcZsQlrRel.class);
                    example.createCriteria().andEqualTo("qlrid", qlrid);
                    List<BdcZsQlrRel> bdcZsQlrRelList = entityMapper.selectByExampleNotNull(example);
                    if (CollectionUtils.isNotEmpty(bdcZsQlrRelList)) {
                        for (BdcZsQlrRel bdcZsQlrRel : bdcZsQlrRelList) {
                            List<BdcZs> bdcZsList = bdcZsService.getBdcZsByProid(proid);
                            if (CollectionUtils.isNotEmpty(bdcZsList) && CollectionUtils.size(bdcZsList) > 1) {
                                bdcZsService.deleteBdcZs(bdcZsQlrRel.getZsid());
                                example = new Example(BdcXmzsRel.class);
                                example.createCriteria().andEqualTo("zsid", bdcZsQlrRel.getZsid());
                                entityMapper.deleteByExampleNotNull(example);
                            }
                            bdcZsList = bdcZsService.getBdcZsByProid(proid);
                            if (CollectionUtils.isNotEmpty(bdcZsList) && CollectionUtils.size(bdcZsList) == 1) {
                                BdcXm bdcXm = bdcXmService.getBdcXmByProid(proid);
                                bdcXm.setSqfbcz("否");
                                entityMapper.saveOrUpdate(bdcXm, bdcXm.getProid());
                            }
                        }
                        dataManagerService.deleteByExample(example);
                    }
                } else {
                    Example example = new Example(BdcZsQlrRel.class);
                    example.createCriteria().andEqualTo("qlrid", qlrid);
                    dataManagerService.deleteByExample(example);
                    entityMapper.deleteByPrimaryKey(BdcQlr.class, qlrid);
                }

            } catch (Exception e) {
                result = "fail";
                e.printStackTrace();
            }
        }
        map.put("result", result);
        return map;
    }

    /**
     * @param
     * @author <a href="mailto:lizhi@gtmap.cn">lizhi</a>
     * @rerutn
     * @description 保存权利人信息
     */
    @ResponseBody
    @RequestMapping(value = "/saveBdcQlrxx", method = RequestMethod.POST)
    public Map<String, String> saveBdcQlrxx(Model model, String bdcQlrs, String delQlrid, String sqfbcz, String gyfs, String proid, String djId, String bdcdyh, String bdclx, String qllx, String bdcdyFwlx) {
        Map<String, String> map = Maps.newHashMap();
        String returnValue = "fail";
        if (StringUtils.isNoneBlank(bdcQlrs)) {
            List<BdcQlr> bdcQlrList = JSON.parseArray(bdcQlrs, BdcQlr.class);
            List<BdcQlr> qlrList = Lists.newArrayList();
            List<BdcQlr> ywrList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(bdcQlrList)) {
                for (BdcQlr bdcQlr : bdcQlrList) {
                    if (bdcQlr != null && StringUtils.isNoneBlank(bdcQlr.getQlrid())) {
                        if (StringUtils.equals(bdcQlr.getQlrsfzjzl(), "1") && !IDValidator.isValidatedAllIdcard(bdcQlr.getQlrzjh())) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", bdcQlr.getQlrmc() + "身份证不合法！");
                            return map;
                        }
                        BdcQlr tempBdcQlr = entityMapper.selectByPrimaryKey(BdcQlr.class, bdcQlr.getQlrid());
                        if (tempBdcQlr == null) {
                            bdcQlr.setQlrid(UUIDGenerator.generate18());
                        }
                        if (StringUtils.equals(bdcQlr.getQlrlx(), Constants.QLRLX_QLR)) {
                            qlrList.add(bdcQlr);
                        } else if (StringUtils.equals(bdcQlr.getQlrlx(), Constants.QLRLX_YWR)) {
                            ywrList.add(bdcQlr);
                        }
                    } else {
                        map.put("msg", returnValue);
                        map.put("msgInfo", "存在非法数据！");
                        return map;
                    }
                }
                if (StringUtils.equals(sqfbcz, Constants.FLAG_YES_CHINESE)) {
                    if (CollectionUtils.isNotEmpty(qlrList) && CollectionUtils.size(qlrList) == 1) {
                        map.put("msg", returnValue);
                        map.put("msgInfo", "无效的分别持证方式！");
                        return map;
                    }
                    if (StringUtils.equals(qllx, Constants.QLLX_CFDJ) || StringUtils.equals(qllx, Constants.QLLX_DYAQ)) {
                        map.put("msg", returnValue);
                        map.put("msgInfo", "无效的分别持证方式！");
                        return map;
                    }
                    for (BdcQlr bdcQlr : qlrList) {
                        if (!StringUtils.equals(bdcQlr.getSfczr(), Constants.FLAG_YES_CHINESE)) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", "分别持证方式下是否持证人无法修改为否！");
                            return map;
                        }
                    }
                } else {
                    if (!(StringUtils.equals(qllx, Constants.QLLX_DYAQ) || StringUtils.equals(qllx, Constants.QLLX_CFDJ))) {
                        int count = 0;
                        for (BdcQlr bdcQlr : qlrList) {
                            if (StringUtils.equals(bdcQlr.getSfczr(), Constants.FLAG_YES_CHINESE)) {
                                count++;
                            }
                        }
                        if (count != 1) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", "请确定正确的持证人！");
                            return map;
                        }
                    }
                }
                if (StringUtils.equals(gyfs, Constants.GYFS_DDGY_DM) && CollectionUtils.isNotEmpty(qlrList) && CollectionUtils.size(qlrList) > 1) {
                    map.put("msg", returnValue);
                    map.put("msgInfo", "无效的共有方式！");
                    return map;
                } else if (StringUtils.equals(gyfs, Constants.GYFS_AFGY_DM)) {
                    if (CollectionUtils.size(qlrList) == 1) {
                        map.put("msg", returnValue);
                        map.put("msgInfo", "无效的共有方式！");
                        return map;
                    } else if (CollectionUtils.isNotEmpty(qlrList)) {
                        Double gybl = null;
                        for (BdcQlr bdcQlr : qlrList) {
                            try {
                                if (gybl == null) {
                                    gybl = CommonUtil.getGybl(bdcQlr.getQlbl());
                                } else {
                                    gybl += CommonUtil.getGybl(bdcQlr.getQlbl());
                                }
                            } catch (Exception e) {
                                map.put("msg", returnValue);
                                map.put("msgInfo", "无效的共有比例！");
                                return map;
                            }
                        }
                        if (gybl == null) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", "无效的共有比例！");
                            return map;
                        }
                        if (Double.compare(gybl, Double.parseDouble("1")) != 0) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", "无效的共有比例！");
                            return map;
                        }
                    }
                } else if (StringUtils.equals(gyfs, Constants.GYFS_GTGY_DM)) {
                    for (BdcQlr bdcQlr : qlrList) {
                        if (StringUtils.isNoneBlank(bdcQlr.getQlbl())) {
                            map.put("msg", returnValue);
                            map.put("msgInfo", "无效的共有比例！");
                            return map;
                        }
                    }
                }
                if (StringUtils.isBlank(proid)) {
                    String cqQllx = ReadXmlProps.getQllx(StringUtils.substring(bdcdyh, 12, 14), StringUtils.substring(bdcdyh, 19, 20));
                    if (StringUtils.equals(cqQllx, qllx)) {
                        QllxVo qllxVo = qllxService.initPropertyRight(bdcdyh, bdclx, djId, bdcdyFwlx);
                        if (qllxVo != null) {
                            qllxVo.setGyqk(gyfs);
                            entityMapper.saveOrUpdate(qllxVo, qllxVo.getQlid());
                            proid = qllxVo.getProid();
                            if (CollectionUtils.isNotEmpty(qlrList)) {
                                for (BdcQlr bdcQlr : qlrList) {
                                    bdcQlr.setProid(proid);
                                }
                            }
                            if (CollectionUtils.isNotEmpty(ywrList)) {
                                for (BdcQlr bdcQlr : ywrList) {
                                    bdcQlr.setProid(proid);
                                }
                            }
                        }
                    }
                } else {
                    BdcXm bdcXm = entityMapper.selectByPrimaryKey(BdcXm.class, proid);
                    if (bdcXm != null) {
                        QllxVo qllxVo = qllxService.queryQllxVo(bdcXm);
                        if (qllxVo != null) {
                            qllxVo.setGyqk(gyfs);
                            entityMapper.saveOrUpdate(qllxVo, qllxVo.getQlid());
                        }
                    }
                }
                if (StringUtils.isNoneBlank(delQlrid)) {
                    entityMapper.deleteByPrimaryKey(BdcQlr.class, delQlrid);
                }
                if (StringUtils.equals(qllx, Constants.QLLX_CFDJ)) {
                    if (CollectionUtils.isNotEmpty(qlrList)) {
                        for (BdcQlr bdcQlr : qlrList) {
                            logService.saveOrUpdateLog(bdcQlr);
                            entityMapper.saveOrUpdate(bdcQlr, bdcQlr.getQlrid());
                        }
                    }
                } else if (CollectionUtils.isNotEmpty(qlrList)) {
                    List<BdcZs> bdcZsList = bdcZsService.getBdcZsByProid(proid);
                    if (StringUtils.equals(sqfbcz, Constants.FLAG_YES_CHINESE)) {
                        if (CollectionUtils.isNotEmpty(qlrList) && CollectionUtils.size(qlrList) > 1) {
                            if (CollectionUtils.isNotEmpty(bdcZsList) && CollectionUtils.size(bdcZsList) == CollectionUtils.size(qlrList)) {
                                for (BdcQlr bdcQlr : qlrList) {
                                    bdcQlr.setSfczr(Constants.FLAG_YES_CHINESE);
                                    logService.saveOrUpdateLog(bdcQlr);
                                    entityMapper.saveOrUpdate(bdcQlr, bdcQlr.getQlrid());
                                    for (BdcZs bdcZs : bdcZsList) {
                                        Example example = new Example(BdcZsQlrRel.class);
                                        example.createCriteria().andEqualTo("qlrid", bdcQlr.getQlrid()).andEqualTo("zsid", bdcZs.getZsid());
                                        List<BdcZsQlrRel> bdcZsQlrRelList = entityMapper.selectByExampleNotNull(example);
                                        if (CollectionUtils.isNotEmpty(bdcZsQlrRelList)) {
                                            bdcZs.setCzr(bdcQlr.getQlrmc());
                                            bdcZs.setCzrid(bdcQlr.getQlrid());
                                            logService.saveOrUpdateLog(bdcZs);
                                            entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
                                        }
                                    }
                                }
                            } else if (CollectionUtils.isNotEmpty(bdcZsList)) {
                                for (BdcQlr bdcQlr : qlrList) {
                                    bdcQlr.setSfczr(Constants.FLAG_YES_CHINESE);
                                    logService.saveOrUpdateLog(bdcQlr);
                                    entityMapper.saveOrUpdate(bdcQlr, bdcQlr.getQlrid());
                                }
                                List<BdcZs> tempBdcZsList = Lists.newArrayList();
                                tempBdcZsList.addAll(bdcZsList);
                                List<BdcQlr> tempBdcQlrList = Lists.newArrayList();
                                tempBdcQlrList.addAll(qlrList);
                                for (BdcZs bdcZs : bdcZsList) {
                                    for (BdcQlr bdcQlr : qlrList) {
                                        if (StringUtils.equals(bdcZs.getCzrid(), bdcQlr.getQlrid())) {
                                            bdcZs.setCzr(bdcQlr.getQlrmc());
                                            bdcZs.setCzrid(bdcQlr.getQlrid());
                                            logService.saveOrUpdateLog(bdcZs);
                                            entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
                                            tempBdcZsList.remove(bdcZs);
                                            tempBdcQlrList.remove(bdcQlr);
                                            break;
                                        }
                                    }
                                }
                                if (CollectionUtils.isNotEmpty(tempBdcZsList)) {
                                    for (int i = 0; i < tempBdcZsList.size(); i++) {
                                        BdcZs bdcZs = tempBdcZsList.get(0);
                                        BdcQlr bdcQlr = tempBdcQlrList.get(0);
                                        bdcZs.setCzr(bdcQlr.getQlrmc());
                                        bdcZs.setCzrid(bdcQlr.getQlrid());
                                        logService.saveOrUpdateLog(bdcZs);
                                        entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
                                        tempBdcQlrList.remove(bdcQlr);
                                    }
                                }
                                for (BdcQlr bdcQlr : tempBdcQlrList) {
                                    manageCertificateService.generateSingleCertificateRel(bdcZsList.get(0), bdcQlr);
                                }
                                List<BdcZs> handleBdcZsList = bdcZsService.getBdcZsByProid(proid);
                                manageCertificateService.deleteBdcXmzsRelByProid(proid);
                                if (CollectionUtils.isNotEmpty(handleBdcZsList)) {
                                    for (BdcZs bdcZs : handleBdcZsList) {
                                        manageCertificateService.deleteBdcZsQlrRelByZsid(bdcZs.getZsid());
                                        BdcXmzsRel bdcXmzsRel = new BdcXmzsRel();
                                        bdcXmzsRel.setXmzsgxid(UUIDGenerator.generate18());
                                        bdcXmzsRel.setProid(proid);
                                        bdcXmzsRel.setZsid(bdcZs.getZsid());
                                        entityMapper.saveOrUpdate(bdcXmzsRel, bdcXmzsRel.getXmzsgxid());
                                        BdcZsQlrRel bdcZsQlrRel = new BdcZsQlrRel();
                                        bdcZsQlrRel.setGxid(UUIDGenerator.generate18());
                                        bdcZsQlrRel.setQlrid(bdcZs.getCzrid());
                                        bdcZsQlrRel.setZsid(bdcZs.getZsid());
                                        entityMapper.saveOrUpdate(bdcZsQlrRel, bdcZsQlrRel.getGxid());
                                    }
                                }
                            }
                        }
                    } else if (CollectionUtils.isNotEmpty(bdcZsList)) {
                        for (BdcQlr bdcQlr : qlrList) {
                            logService.saveOrUpdateLog(bdcQlr);
                            entityMapper.saveOrUpdate(bdcQlr, bdcQlr.getQlrid());
                        }
                        if (CollectionUtils.size(bdcZsList) > 1 && CollectionUtils.size(qlrList) > 1) {
                            BdcZs keepBdcZs = null;
                            for (BdcQlr tempBdcQlr : qlrList) {
                                for (BdcZs tempBdcZs : bdcZsList) {
                                    if (StringUtils.equals(tempBdcQlr.getSfczr(), Constants.FLAG_YES_CHINESE) && StringUtils.equals(tempBdcQlr.getQlrmc(), tempBdcZs.getCzr()) && StringUtils.equals(tempBdcQlr.getQlrid(), tempBdcZs.getCzrid())) {
                                        keepBdcZs = tempBdcZs;
                                    }
                                }
                            }
                            if (keepBdcZs == null) {
                                keepBdcZs = bdcZsList.get(0);
                            }
                            BdcZs[] bdcZsArray = new BdcZs[bdcZsList.size()];
                            for (int i = 0; i < bdcZsList.size(); i++) {
                                bdcZsArray[i] = bdcZsList.get(i);
                            }
                            manageCertificateService.deleteBdcZs(bdcZsArray);
                            entityMapper.saveOrUpdate(keepBdcZs, keepBdcZs.getZsid());
                            manageCertificateService.generateSingleCertificateRel(keepBdcZs, proid);
                        } else {
                            manageCertificateService.generateSingleCertificateRel(bdcZsList.get(0), proid);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(ywrList)) {
                    for (BdcQlr bdcQlr : ywrList) {
                        logService.saveOrUpdateLog(bdcQlr);
                        entityMapper.saveOrUpdate(bdcQlr, bdcQlr.getQlrid());
                    }
                }
                BdcXm bdcXm = bdcXmService.getBdcXmByProid(proid);
                bdcXm.setSqfbcz(sqfbcz);
                entityMapper.saveOrUpdate(bdcXm, bdcXm.getProid());
                returnValue = "success";
                map.put("msg", returnValue);
            } else {
                if (StringUtils.isNoneBlank(proid)) {
                    Example example = new Example(BdcQlr.class);
                    example.createCriteria().andEqualTo("proid", proid).andEqualTo("qlrlx", "qlr");
                    entityMapper.deleteByExampleNotNull(example);
                    example.createCriteria().andEqualTo("proid", proid).andEqualTo("qlrlx", "ywr");
                    entityMapper.deleteByExampleNotNull(example);
                }
            }
        }
        return map;
    }
}
