package com.th.demo.service.impl.finance;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.th.demo.mapping.common.CommonMapper;
import com.th.demo.mapping.finance.AccountDetailMapper;
import com.th.demo.mapping.finance.AccountMapper;
import com.th.demo.mapping.finance.InvoiceNewMapper;
import com.th.demo.mapping.finance.VerifyAccountMapper;
import com.th.demo.mapping.ware.OutRecordMapper;
import com.th.demo.model.finance.*;
import com.th.demo.model.system.SysUser;
import com.th.demo.service.finance.AccountService;
import com.th.demo.tools.JSONTools;
import com.th.demo.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("AccountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    AccountDetailMapper accountDetailMapper;
    @Autowired
    CommonMapper commonMapper;

    @Autowired
    VerifyAccountMapper verifyAccountMapper;
    @Autowired
    InvoiceNewMapper invoiceNewMapper;

    @Autowired
    OutRecordMapper outRecordMapper;

    String result = "";

    int num = 0;

    @Override
    public String query(int page, int rows, String customerName, String userId, String belongId, String accountFlag) {
        PageHelper.startPage(page, rows);
        List<AccountWithInvoice> list = accountMapper.selectWithInvoice(customerName,belongId,accountFlag);
        PageInfo<AccountWithInvoice> pageInfo = new PageInfo<>(list);
        result = JSONTools.toStringyyyyMMddHHmmss(pageInfo);
        return result;
    }

    @Override
    public String account(String json, String userId, String belongId) {
        num = 0;
        List<AccountDetail> list = JSON.parseObject(json, new TypeReference<List<AccountDetail>>() {
        });
        Double unitPrice = 0.0;
        Double price = 0.0;
        Double accountWeight = 0.0;
        String pk = commonMapper.selectPrimaryKey();

        AccountDetail accountDetail = null;
        for (int i = 0; i < list.size(); i++) {
            accountDetail = list.get(i);
            if (accountDetail.getSuttle() == 0.0) {
                accountWeight += accountDetail.getWeight();
            } else {
                accountWeight += accountDetail.getSuttle();
            }
            price += accountDetail.getTotalPrice();

            accountDetail.setfId(pk);
            accountDetail.setAccountFlag("1");
            accountDetailMapper.updateByPrimaryKey(accountDetail);
        }
        Account account = getAccount(pk, list.get(0).getCustomerName(), price, accountWeight, userId, belongId);
        num += accountMapper.insert(account);
        return Tools.moreThanZeroResultJSON(num);
    }

    @Override
    public String queryGroup(int page, int rows, String customerName, String userId, String belongId, String accountFlag) {
        PageHelper.startPage(page, rows);
        List<AccountWithInvoice> list = accountMapper.queryGroup(customerName,belongId,accountFlag);
        PageInfo<AccountWithInvoice> pageInfo = new PageInfo<>(list);
        result = JSONTools.toStringyyyyMMddHHmmss(pageInfo);
        return result;
    }

    @Override
    public String queryBycustomer(String customerName, String userId, String belongId, String accountFlag) {

        List<AccountWithInvoice> list = accountMapper.queryBycustomer(customerName,belongId,accountFlag);
        result = JSONTools.toStringyyyyMMddHHmmss(list);
        return result;
    }

    @Override
    public String queryVerifyAccount(String queryDateFrom, String queryDateTo, String fkComponeyName, String userId, String belongId) {
        List<VerifyAccount> list = verifyAccountMapper.selectAccount(queryDateFrom,queryDateTo,fkComponeyName,userId,belongId);
        result = JSONTools.toStringyyyyMMddHHmmss(list);
        return result;
    }

    @Override
    public String writeInvoice(String json, String userId, String belongId, String invoiceCmp, String invoiceDate, String invoiceAmt) {
        List<VerifyAccount> list = JSON.parseObject(json, new TypeReference<List<VerifyAccount>>() {
        });
        int num = 0;
        VerifyAccount verifyAccount = new VerifyAccount();
        for (VerifyAccount acc:list ) {
           // verifyAccount = verifyAccountMapper.selectByPrimaryKey(acc.getUuid());
            if(acc.getInvoiceDate() != null && acc.getInvoiceDate().length() > 0){
                return JSONTools.toString(1,acc.getPlateNo()+"已开票，请勿重复操作");
            }
            acc.setInvoiceCompany(invoiceCmp);
            acc.setInvoiceDate(invoiceDate);
            acc.setWriteInvoiceAmt(acc.getInvoiceAmt());
            acc.setInvoiceCrtTime(new Date());
            // acc.setInvoiceId(invoiceNew.getUuid());
            num += verifyAccountMapper.updateWriteInvocieInfo(acc);
        }
        return Tools.moreThanZeroResultJSON(num);
    }

    @Override
    public String writeRcvPay(String json, String userId, String belongId, String rcvPayMth, String rcvPayDate, String invoiceAmt) {
        List<VerifyAccount> list = JSON.parseObject(json, new TypeReference<List<VerifyAccount>>() {});
        for (VerifyAccount acc:list ) {
            if(acc.getRcvPayDate() != null&&acc.getRcvPayDate().length() > 0){
                return JSONTools.toString(1,acc.getPlateNo()+"已付款，请勿重复操作");
            }
            acc.setRcvPayMth(rcvPayMth);
            acc.setRcvPayAmt(acc.getWriteInvoiceAmt());
            acc.setRcvPayDate(rcvPayDate);
            acc.setRcvPayCrtTime(new Date());
            num += verifyAccountMapper.updateRcvPayInfo(acc);
        }
        return Tools.moreThanZeroResultJSON(num);
    }

    @Override
    public String queryInvoiceRslt(String queryDateFrom, String queryDateTo, String fkComponeyName, String userId, String belongId) {
        List<VerifyAccount> list = verifyAccountMapper.queryInvoiceRslt(queryDateFrom,queryDateTo,fkComponeyName,userId,belongId);
        result = JSONTools.toStringyyyyMMddHHmmss(list);
        return result;
    }

    @Override
    public String queryProgress(String queryDateFrom, String queryDateTo, String fkComponeyName, String userId, String belongId) {
        List<VerifyAccountProgress> list = verifyAccountMapper.queryProgress(queryDateFrom,queryDateTo,fkComponeyName,userId,belongId);
        result = JSONTools.toStringyyyyMMddHHmmss(list);
        return result;
    }

    @Override
    public String backProgress(String json, String bachType, String userId, String belongId) {
        List<VerifyAccount> list = JSON.parseObject(json, new TypeReference<List<VerifyAccount>>() {});
        num = 0;
        Date now = new Date();
        String msg = "";
        if(bachType.equals("VerifyAcc")){
            for(VerifyAccount acc:list){
                if(now.getTime() - acc.getCrtTime().getTime() > 24*60*60*1000){
                    msg = "钢板号："+acc.getPlateNo()+"对账时间超过24小时，只有管理员账号可以撤回";
                }
            }
        }else if(bachType.equals("Invoice")){
            for(VerifyAccount acc:list){
                if(now.getTime() - acc.getInvoiceCrtTime().getTime() > 24*60*60*1000){
                    msg = "钢板号："+acc.getPlateNo()+"开票时间超过24小时，只有管理员账号可以撤回";
                }
            }
        }else if(bachType.equals("RcvPay")){
            for(VerifyAccount acc:list){
                if(now.getTime() - acc.getRcvPayCrtTime().getTime() > 24*60*60*1000){
                    msg = "钢板号："+acc.getPlateNo()+"付款时间超过24小时，只有管理员账号可以撤回";
                }
            }
        }
        if(!(userId.equals("1")||userId.equals("5ce1270696f011e9bc37525400b9b20a")) && msg.length() > 0){
            return JSONTools.toString(1,msg);
        }
        if(bachType.equals("VerifyAcc")){
            for(VerifyAccount acc:list){
                num += verifyAccountMapper.backVerifyAcc(acc);
                outRecordMapper.cleanVerifyInfo(acc.getOutRcdId());
            }
        }else if(bachType.equals("Invoice")){
            for(VerifyAccount acc:list){
                num += verifyAccountMapper.backInvoice(acc);
            }
        }else if(bachType.equals("RcvPay")){
            for(VerifyAccount acc:list){
                num += verifyAccountMapper.backRcvPay(acc);
            }
        }
        return Tools.moreThanZeroResultJSON(num);
    }

    @Override
    public String deleteInvoice(String json, String userId, String belongId) {
        if(!(userId.equals("1")||userId.equals("5ce1270696f011e9bc37525400b9b20a"))){
            return JSONTools.toString(1,"账号无权限进行删除操作");
        }
        List<VerifyAccount> list = JSON.parseObject(json, new TypeReference<List<VerifyAccount>>() {});
        for(VerifyAccount acc:list){
            num += verifyAccountMapper.backVerifyAcc(acc);
            outRecordMapper.cleanVerifyInfo(acc.getOutRcdId());
        }
        return Tools.moreThanZeroResultJSON(num);
    }


    private Account getAccount(String pk, String customerName, Double price, Double accountWeight, String userId, String belongId) {
        Account account = new Account();
        account.setId(pk);
        account.setCustomerName(customerName);
        account.setPrice(price);
        account.setWeight(accountWeight);
        account.setUnitPrice(price / accountWeight);
        account.setAddUser(new SysUser(userId));
        account.setAddTime(new Date());
        account.setCancelFlag("0");
        account.setBelongId(belongId);
        return  account;
    }
}
