package com.dxhy.base.service.tdxtaxcurrent;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.base.dao.BaseSysEnterpriseConfigDao;
import com.dxhy.base.dao.BaseTDxTaxCurrentDao;
import com.dxhy.base.dao.BaseTDxTaxHandlelogDao;
import com.dxhy.base.entity.BaseTDxTaxCurrent;
import com.dxhy.base.entity.BaseTDxTaxHandlelog;
import com.dxhy.base.model.BaseQyxxlbRespVO;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.SbzqEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.api.model.config.sys.DictdetaModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 * 企业信息查询业务处理类
 *
 * @author zhanghong
 * @date 2019年4月25日
 *
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaLowerCamelCaseVariableNaming",
    "AlibabaClassNamingShouldBeCamel"})
@Service("baseITDxTaxCurrentService")
public class BaseTDxTaxCurrentServiceImpl extends MpBaseServiceImpl<BaseTDxTaxCurrentDao, BaseTDxTaxCurrent>
    implements BaseITDxTaxCurrentService {

    @Resource
    private BaseTDxTaxHandlelogDao baseTDxTaxHandlelogDao;

    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Autowired
    private BaseSysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Override
    public String getTaxCurrent(Map<String, Object> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        String gfsh = (String)pramsMap.get("gfsh");
        QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("taxno", gfsh);
        BaseTDxTaxCurrent current = super.baseMapper.selectOne(queryWrapper);
        if (current != null) {
            String selectStartDate = current.getSelectStartDate();
            String selectEndDate = current.getSelectEndDate();
            String operationEndDate = current.getOperationEndDate();
            selectStartDate = LocalDate.parse(selectStartDate, DateTimeFormatter.ofPattern("yyyyMMdd"))
                .format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
            selectEndDate = LocalDate.parse(selectEndDate, DateTimeFormatter.ofPattern("yyyyMMdd"))
                .format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
            operationEndDate = LocalDate.parse(operationEndDate, DateTimeFormatter.ofPattern("yyyyMMdd"))
                .format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
            current.setSelectStartDate(selectStartDate);
            current.setSelectEndDate(selectEndDate);
            current.setOperationEndDate(operationEndDate);
        }
        JSONObject json = new JSONObject();
        json.put("current", current);
        return super.responseResult(json);
    }

    @Override
    public String selectByCxtj(Map<String, Object> pramsMap, int curr, int size, int count) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);
        // 需要设置返回列表标题时调用
        List<String> list = (List<String>)pramsMap.get("gfsh");
        if (list == null || list.size() == 0) {
            json.put("datalist", new ArrayList<BaseQyxxlbRespVO>());
            // 设置记录总数
            json.put("total", 0);
            return super.responseResult(json);
        }
        Page<BaseTDxTaxCurrent> page = new Page<>(curr, size);

        QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
        if (pramsMap.containsKey("gfsh") && !StringHelper.isBlank(String.valueOf(pramsMap.get("gfsh")))) {
            String[] values = list.toArray(new String[0]);
            queryWrapper.in("taxno", values);
        }
        if (pramsMap.containsKey("xydj") && !StringHelper.isBlank(String.valueOf(pramsMap.get("xydj")))) {
            queryWrapper.eq("credit_rating", pramsMap.get("xydj"));
        }
        if (pramsMap.containsKey("sbzq") && !StringHelper.isBlank(String.valueOf(pramsMap.get("sbzq")))) {
            queryWrapper.eq("declare_period", pramsMap.get("sbzq"));
        }
        queryWrapper.orderByAsc("taxno");

        IPage<BaseTDxTaxCurrent> pageInfo = super.page(page, queryWrapper);
        List<BaseTDxTaxCurrent> resultList = pageInfo.getRecords();

        List<BaseQyxxlbRespVO> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {

            for (int i = 0; i < resultList.size(); i++) {
                int current = (int)pageInfo.getCurrent();
                int s = (int)pageInfo.getSize();
                int xh = (current - 1) * s + i + 1;
                BaseQyxxlbRespVO qylb = this.convertToQylbView(resultList.get(i), xh);
                returnList.add(qylb);
            }
        }
        json.put("datalist", returnList);
        // 设置记录总数
        json.put("total", pageInfo.getTotal());
        return super.responseResult(json);
    }

    private BaseQyxxlbRespVO convertToQylbView(BaseTDxTaxCurrent tDxTaxCurrent, int i) {
        BaseQyxxlbRespVO qyxx = new BaseQyxxlbRespVO();
        qyxx.setId(String.valueOf(i));
        qyxx.setXh(String.valueOf(i));
        qyxx.setGfmc(tDxTaxCurrent.getTaxname());
        qyxx.setGfsh(tDxTaxCurrent.getTaxno());
        qyxx.setGxjsrq(tDxTaxCurrent.getSelectEndDate());
        qyxx.setGxksrq(tDxTaxCurrent.getSelectStartDate());
        qyxx.setJsh(tDxTaxCurrent.getOldTaxNo());
        qyxx.setSbzq(SBZQ_MAP.get(tDxTaxCurrent.getDeclarePeriod()));
        qyxx.setSkssq(tDxTaxCurrent.getCurrentTaxPeriod());
        qyxx.setSsqjsrq(tDxTaxCurrent.getOperationEndDate());
        qyxx.setXydj(tDxTaxCurrent.getCreditRating());
        qyxx.setSdzt(tDxTaxCurrent.getLatchStatus());
        qyxx.setZse(tDxTaxCurrent.getLimitDkse() == null ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxTaxCurrent.getLimitDkse().toPlainString())));
        qyxx.setNewBussiPwd(tDxTaxCurrent.getNewBussiPwd());

        //字典转换
        qyxx.setCompanyType(dictdetaServcice.queryDictName(DictConstant.COMPANY_TYPE,tDxTaxCurrent.getCompanyType()));
        qyxx.setOilType(dictdetaServcice.queryDictName(DictConstant.OIL_TYPE,tDxTaxCurrent.getOilType()));
        qyxx.setTaxpayerType(dictdetaServcice.queryDictName(DictConstant.TAXPAYER_TYPE,tDxTaxCurrent.getTaxpayerType()));
        qyxx.setSyncTime(tDxTaxCurrent.getSyncTime());
//        List<DictdetaModel> sbzts = dictdetaServcice.selectDictdeta("sbzt");
        List<DictdetaModel> sbzts = dictdetaServcice.selectDictdeta(DictConstant.DECLARE);
        String periodIndexInfo = tDxTaxCurrent.getPeriodIndexInfo();
        String monthIndexInfo = tDxTaxCurrent.getMonthIndexInfo();
        if (StringUtils.isNotBlank(periodIndexInfo)) {
            String period = periodIndexInfo.substring(periodIndexInfo.lastIndexOf("_") + 1);
            for (DictdetaModel model : sbzts) {
                if (model.getDictcode().equals(period)) {
                    qyxx.setPeriodIndexInfo(
                        periodIndexInfo.substring(0, periodIndexInfo.lastIndexOf("_") + 1) + model.getDictname());
                }
            }
        }
        if (StringUtils.isNotBlank(monthIndexInfo)) {
            String month = monthIndexInfo.substring(monthIndexInfo.lastIndexOf("_") + 1);
            for (DictdetaModel model : sbzts) {
                if (model.getDictcode().equals(month)) {
                    qyxx.setMonthIndexInfo(
                        monthIndexInfo.substring(0, monthIndexInfo.lastIndexOf("_") + 1) + model.getDictname());
                }
            }
        }
        //是否是乐企税号
        qyxx.setSelect(false);
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", tDxTaxCurrent.getTaxno()));
        if (sysEnterpriseConfigEntity != null&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
            qyxx.setSelect(true);
            //置空勾选开始，结束，所属期结束日期
            qyxx.setGxksrq("");
            qyxx.setGxjsrq("");
            qyxx.setSsqjsrq("");
        }
        return qyxx;
    }

    /**
     * 申报周期类型放入map集合中
     */
    public static final Map<String, String> SBZQ_MAP = new LinkedHashMap<String, String>() {
        {
            for (SbzqEnum en : SbzqEnum.values()) {
                this.put(en.getSbzqDm(), en.getSbzqMc(en.getIndex()));
            }
        }
    };

    @Override
    public String updateByGfsh(Map<String, Object> pramsMap) {
        UpdateWrapper<BaseTDxTaxCurrent> updateWrapper = new UpdateWrapper<>();
        QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
        String sdzt = (String)pramsMap.get("sdzt");
        queryWrapper.eq("taxno", pramsMap.get("gfsh"));
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        BaseTDxTaxCurrent tdxTaxCurrent = super.getOne(queryWrapper);
        BaseTDxTaxHandlelog tdxtaxHandlelog = new BaseTDxTaxHandlelog();
        JSONObject json = new JSONObject();

        if ("1".equals(sdzt)) {
            tdxTaxCurrent.setLatchStatus("0");
            tdxtaxHandlelog.setHandleType("0");
        }
        if ("0".equals(sdzt)) {
            tdxTaxCurrent.setLatchStatus("1");
            tdxtaxHandlelog.setHandleType("1");
        }

        tdxtaxHandlelog.setUserAccount((String)pramsMap.get("userName"));
        tdxtaxHandlelog.setUserName((String)pramsMap.get("userName"));
        tdxtaxHandlelog.setHandleTime(DateUtils.getSqlDate());
        tdxtaxHandlelog.setPeriod(tdxTaxCurrent.getCurrentTaxPeriod());
        tdxtaxHandlelog.setTaxno((String)pramsMap.get("gfsh"));

        updateWrapper.eq("taxno", pramsMap.get("gfsh"));
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        boolean update = super.update(tdxTaxCurrent, updateWrapper);
        if (update) {
            json.put("datalist", "操作成功！");
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            baseTDxTaxHandlelogDao.insert(tdxtaxHandlelog);
        } else {
            json.put("datalist", "操作失败！");
        }

        return super.responseResult(json);
    }

    @Override
    public String updateLimit(Map<String, Object> pramsMap) {
        UpdateWrapper<BaseTDxTaxCurrent> updateWrapper = new UpdateWrapper<>();
        QueryWrapper<BaseTDxTaxCurrent> queryWrapper = new QueryWrapper<>();
        String dkse = (String)pramsMap.get("dkse");
        queryWrapper.eq("taxno", pramsMap.get("gfsh"));
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        BaseTDxTaxCurrent tdxTaxCurrent = super.getOne(queryWrapper);
        if (dkse != null && !"".equals(dkse)) {

            tdxTaxCurrent.setLimitDkse(new BigDecimal(dkse));
        } else {
            tdxTaxCurrent.setLimitDkse(null);
        }

        JSONObject json = new JSONObject();

        updateWrapper.eq("taxno", pramsMap.get("gfsh"));
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        boolean update = super.update(tdxTaxCurrent, updateWrapper);
        if (update) {
            json.put("datalist", "设置成功！");

        } else {
            json.put("datalist", "设置失败！");
        }

        return super.responseResult(json);
    }

}
