package com.dxhy.sign.service.fpqs.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.sign.dao.SignInvoiceDao;
import com.dxhy.sign.dao.SignInvoiceDelDao;
import com.dxhy.sign.dao.SignRecordInvoiceDao;
import com.dxhy.sign.entity.TDxInvoice;
import com.dxhy.sign.entity.TDxInvoiceDel;
import com.dxhy.sign.entity.TDxRecordInvoice;
import com.dxhy.sign.model.SgqsWqsfpVO;
import com.dxhy.sign.service.elec.SignElecInvoiceService;
import com.dxhy.sign.service.fpqs.YlSignService;
import com.dxhy.sign.service.singletable.SignInvoiceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @author liudan
 * @date 2020/12/8
 */
@Service
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})

public class YlSignServiceImpl extends MpBaseServiceImpl<SignRecordInvoiceDao, TDxRecordInvoice>
    implements YlSignService {

    @Resource
    private SignInvoiceDao signInvoiceDao;

    @Resource
    private SignInvoiceService signInvoiceSmService;

    @Resource
    private SignElecInvoiceService signElecInvoiceService;

    @Resource
    private SignInvoiceDelDao signInvoiceDelDao;
    @Value("${dxhy.datasource.dxhy_admin:dxhy_admin}")
    private String dxhyAdmin;

    @Override
    public String ylqsList(Map<String, Object> pramsMap, int curr, int size) {
        String[] titlelist = {"序号", "签收日期", "发票代码", "发票号码", "开票日期", "购方名称", "金额", "税额"};
        String[] titleprop =
            {"xh", "qsDate", "invoiceCode", "invoiceNo", "invoiceDate", "gfName", "invoiceAmount", "taxAmount"};

        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        pramsMap.put("dxhyAdmin", dxhyAdmin);
        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (curr == 1) {
            long hjsl;
            String hjje = "0";
            String hjse = "0";
            List<TDxRecordInvoice> hjList = super.baseMapper.selectYlqsfpHj(pramsMap);
            TDxRecordInvoice hjxx = hjList.get(0);
            hjsl = hjxx.getId();
            if (hjsl != 0) {
                hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));
            }
            json.put("hjsl", hjsl);
            json.put("hjje", hjje);
            json.put("hjse", hjse);
            if (0 == hjsl) {
                json.put("total", 0);
                json.put("datalist", "");
                return super.responseResult(json);
            }
        }

        PageHelper.startPage(curr, size);
        List<SgqsWqsfpVO> pageList = super.baseMapper.selectYlqsfp(pramsMap);
        PageInfo<SgqsWqsfpVO> pageInfo = new PageInfo<>(pageList);
        List<SgqsWqsfpVO> resultList = pageInfo.getList();

        // 设置记录总数
        json.put("total", pageInfo.getTotal());

        if (resultList != null && resultList.size() > 0) {

            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).setXh(String.valueOf(start + i));
            }
        }
        json.put("datalist", resultList);
        return super.responseResult(json);
    }

    @SuppressWarnings("AlibabaMethodTooLong")
    @Override
    public String ylDel(Map<String, String> pramsMap) {
        JSONObject invoiceDetail = JSONObject.parseObject(pramsMap.get("uuids"));
        JSONArray detailArray = (JSONArray)invoiceDetail.get("uuids");

        List<String> idList = new ArrayList<>(detailArray.size());
        for (Object o : detailArray) {
            JSONObject idJson = (JSONObject)o;
            idList.add(idJson.getString("uuid"));
        }
        int failureCount = 0;

        int successCount = 0;
        // 查询扫描信息
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.in("uuid", idList);
        Collection<TDxInvoice> invoiceList = signInvoiceSmService.list(invoiceQueryWrapper);

        for (TDxInvoice tDxInvoice : invoiceList) {

            try {
                boolean deleteElec = false;
                DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                if (FplxEnum.ZP.getFplxDm().equals(tDxInvoice.getInvoiceType())
                    || FplxEnum.DZZP.getFplxDm().equals(tDxInvoice.getInvoiceType())
                    || FplxEnum.JDC.getFplxDm().equals(tDxInvoice.getInvoiceType())
                    || FplxEnum.TXF.getFplxDm().equals(tDxInvoice.getInvoiceType())) {

                    // 更新底账表签收状态为未签收
                    this.baseMapper.updateQsxx(tDxInvoice.getUuid());
                } else {
                    UpdateWrapper<TDxRecordInvoice> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("uuid", tDxInvoice.getUuid());
                    super.remove(updateWrapper);
                }

                deleteElec = signElecInvoiceService.deleteElec(tDxInvoice.getScanId(), pramsMap.get("dbName"));
                if (deleteElec) {
                    successCount++;
                    QueryWrapper<TDxInvoiceDel> query2 = new QueryWrapper<>();
                    query2.eq("uuid", tDxInvoice.getUuid());
                    TDxInvoiceDel selectDel = signInvoiceDelDao.selectOne(query2);

                    DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                    if (selectDel != null) {
                        // 再次删除只更新时间
                        selectDel.setQsDate(tDxInvoice.getQsDate());
                        selectDel.setQsType(tDxInvoice.getQsType());
                        selectDel.setUpdateDate(DateUtils.getSqlDateLong());
                        signInvoiceDelDao.updateById(selectDel);
                    } else {
                        // 存扫描删除表
                        TDxInvoiceDel insertDel = new TDxInvoiceDel();
                        insertDel.setCheckCode(tDxInvoice.getCheckCode());
                        insertDel.setCompany(tDxInvoice.getCompany());
                        insertDel.setCreateDate(DateUtils.getSqlDateLong());
                        insertDel.setGfName(tDxInvoice.getGfName());
                        insertDel.setGfTaxNo(tDxInvoice.getGfTaxNo());
                        insertDel.setInvoiceAmount(tDxInvoice.getInvoiceAmount());
                        insertDel.setInvoiceCode(tDxInvoice.getInvoiceCode());
                        insertDel.setInvoiceDate(tDxInvoice.getInvoiceDate());
                        insertDel.setInvoiceNo(tDxInvoice.getInvoiceNo());
                        insertDel.setInvoiceSerialNo(tDxInvoice.getInvoiceSerialNo());
                        insertDel.setInvoiceType(tDxInvoice.getInvoiceType());
                        insertDel.setNotes(tDxInvoice.getNotes());
                        insertDel.setQsDate(tDxInvoice.getQsDate());
                        insertDel.setQsType(tDxInvoice.getQsType());
                        insertDel.setScanId(tDxInvoice.getScanId());
                        insertDel.setTaxAmount(tDxInvoice.getTaxAmount());
                        insertDel.setTotalAmount(tDxInvoice.getTotalAmount());
                        insertDel.setUpdateDate(DateUtils.getSqlDateLong());
                        insertDel.setUserAccount(tDxInvoice.getUserAccount());
                        insertDel.setUserName(tDxInvoice.getUserName());
                        insertDel.setUuid(tDxInvoice.getUuid());
                        insertDel.setXfName(tDxInvoice.getXfName());
                        insertDel.setXfTaxNo(tDxInvoice.getXfTaxNo());
                        insertDel.setScanDate(tDxInvoice.getCreateDate());

                        signInvoiceDelDao.insert(insertDel);
                    }
                } else {
                    failureCount++;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return "删除成功：" + successCount + "条 \n ; 删除失败：" + failureCount + "条";
    }

    @Override
    public String changeQsDate(Map<String, String> pramsMap) {
        String msg = null;

        JSONObject changeInfo = JSONObject.parseObject(pramsMap.get("changeInfo"));
        JSONArray changeArray = changeInfo.getJSONArray("uuids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");
            uuidList.add(uuid);
        }

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        // 更新底账表业务单元
        TDxRecordInvoice recordInvoice = new TDxRecordInvoice();
        recordInvoice.setQsDate(DateUtils.getNow());
        UpdateWrapper<TDxRecordInvoice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("uuid", uuidList);

        // 更新扫描表业务单元
        TDxInvoice dxInvoice = new TDxInvoice();
        dxInvoice.setQsDate(DateUtils.getNow());
        UpdateWrapper<TDxInvoice> updateDxInvoiceWrapper = new UpdateWrapper<>();
        updateDxInvoiceWrapper.in("uuid", uuidList);
        this.change(recordInvoice, updateWrapper, dxInvoice, updateDxInvoiceWrapper);

        return msg;
    }

    @Transactional(rollbackFor = Exception.class)
    public void change(TDxRecordInvoice recordInvoice, UpdateWrapper<TDxRecordInvoice> updateWrapper,
        TDxInvoice dxInvoice, UpdateWrapper<TDxInvoice> updateDxInvoiceWrapper) {
        super.update(recordInvoice, updateWrapper);
        signInvoiceSmService.update(dxInvoice, updateDxInvoiceWrapper);
    }
}
