package com.zfire.mall.manager.logic.manage.take;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.manage.take.TakerRecordBean;
import com.zfire.mall.manager.commonmapper.manage.take.TakerRecordReserveMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.SMSTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.common.SMSLogic;
import com.zfire.mall.manager.plus.entity.KingDeeCustomer;
import com.zfire.mall.manager.plus.entity.TakerRecord;
import com.zfire.mall.manager.plus.service.CommonFileService;
import com.zfire.mall.manager.plus.service.KingDeeCustomerService;
import com.zfire.mall.manager.plus.service.TakerRecordService;
import com.zfire.mall.manager.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TakerRecordLogic {

    @Resource
    TakerRecordReserveMapper takerRecordReserveMapper;
    @Resource
    TakerRecordService takerRecordService;
    @Resource
    SMSLogic smsLogic;
    @Resource
    RedisUtil redisUtil;
    @Resource
    CommonFileService commonFileService;
    @Resource
    CommonLogic commonLogic;
    @Resource
    KingDeeCustomerService kingDeeCustomerService;

    public IPage<TakerRecordBean> listPage(String customerName, String takerName, String phoneKeyword, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> adminCompanyIds = adminUser.getAdminCompanyIds();
        String customerId = null;
        if (adminUser.getIsCustomer()) {
            customerId = adminUser.getCustomerId();
        }
        return takerRecordReserveMapper.listPage(new Page<>(pageNum, pageSize), adminCompanyIds, customerId, customerName, takerName, phoneKeyword, DateUtil.formatDate(DateUtil.date()));
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(TakerRecordBean takerRecordBean) throws RemoteServiceException {
        KingDeeCustomer customer = kingDeeCustomerService.getById(takerRecordBean.getCustomerId());
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (Objects.isNull(customer)) {
            throw new RemoteServiceException("客户不存在");
        }

        if (takerRecordBean.getExpireTime().compareTo(LocalDate.now()) < 0) {
            throw new RemoteServiceException("有效期不能少于当前日期");
        }

  /*      Object validMessageCode = redisUtil.get(Constant.RedisPrefix.VALIDA_PHONE_SMS + takerRecordBean.getPhone());
        if (Objects.isNull(validMessageCode)) {
            throw new RemoteServiceException("短信验证码过期");
        }

        if (!takerRecordBean.getCode().equals(validMessageCode)) {
            throw new RemoteServiceException("短信验证码错误");
        }
        redisUtil.del(Constant.RedisPrefix.VALIDA_PHONE_SMS + takerRecordBean.getPhone());*/

        TakerRecord takerRecord = new TakerRecord();
        BeanUtils.copyProperties(takerRecordBean, takerRecord);
        if (takerRecordService.lambdaQuery()
                .eq(TakerRecord::getCustomerId, customer.getId())
                .eq(TakerRecord::getPhone, takerRecord.getPhone())
                .count() > 0){
            throw new RemoteServiceException("该手机号已存在，请去重建对应手机号提货人，添加失败");
        }
        takerRecord.setAdminCompanyId(adminUser.getAdminCompanyId());
        takerRecord.setCreateName(adminUser.getNickName());
        takerRecord.setUpdateName(adminUser.getNickName());
        takerRecord.setCustomerName(customer.getName());
        takerRecord.setCustomerNumber(customer.getNumber());

        takerRecord.insert();

//        if (StringUtils.isNotEmpty(takerRecord.getAttach())) {
//            CommonFile commonFile = commonFileService.getOne(new LambdaQueryWrapper<CommonFile>()
//                    .eq(CommonFile::getId, takerRecord.getAttach()));
//            if (Objects.isNull(commonFile)) {
//                throw new RemoteServiceException("附件信息不存在");
//            }
//            commonFile.setObjId(takerRecord.getId())
//                    .setObjType(CommonFileTypeEnum.TAKER_RECORD.toString())
//                    .updateById();

//        }

    }

    public void sendMessageCode(String mobile) throws Exception {
        if (!Validator.isMobile(mobile)) {
            throw new RemoteServiceException("联系电话格式不符");
        }
        // 向手机号发送验证码
        smsLogic.sendSms(Constant.RedisPrefix.VALIDA_PHONE_SMS, mobile, SMSTypeEnum.VALIDA_PHONE_SMS.toString(), Constant.SMS_EXPIRE);
    }

    public void stop(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        takerRecordService.lambdaUpdate()
                .set(TakerRecord::getFlag, 2)
                .set(TakerRecord::getUpdateName, adminUser.getNickName())
                .in(TakerRecord::getAdminCompanyId, adminUser.getAdminCompanyIds())
                .eq(TakerRecord::getFlag, 1)
                .eq(TakerRecord::getId, id)
                .update();
    }

    public ExcelData export(List<TakerRecordBean> records) {
        String[] titles = new String[]{"经销商名称","提货人姓名","身份证","联系电话","备用电话", "有效期", "状态"};
        List<List<Object>> rows = new ArrayList<>();
        for (TakerRecordBean takerRecordBean : records) {
            List<Object> row = new ArrayList<>();
            row.add(takerRecordBean.getCustomerName());
            row.add(takerRecordBean.getTakerName());
            row.add(takerRecordBean.getIdentity());
            row.add(takerRecordBean.getPhone());
            row.add(takerRecordBean.getSparePhone());
            row.add(takerRecordBean.getExpireTime());
            if (takerRecordBean.getFlag() == 0) {
                row.add("失效");
            } else if (takerRecordBean.getFlag() == 1) {
                row.add("有效");
            } else if (takerRecordBean.getFlag() == 2) {
                row.add("停用");
            }
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    @Transactional(rollbackFor = Exception.class)
    public void del(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        takerRecordService.lambdaUpdate().in(TakerRecord::getAdminCompanyId, adminUser.getAdminCompanyIds())
                .in(TakerRecord::getId, ids.stream().distinct().collect(Collectors.toList()))
                .remove();
    }

    public void update(TakerRecordBean takerRecordBean) {
        KingDeeCustomer customer = kingDeeCustomerService.getById(takerRecordBean.getCustomerId());
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (Objects.isNull(customer)) {
            throw new RemoteServiceException("客户不存在");
        }

        if (takerRecordBean.getExpireTime().compareTo(LocalDate.now()) < 0) {
            throw new RemoteServiceException("有效期不能少于当前日期");
        }

        TakerRecord takerRecord = new TakerRecord();
        BeanUtils.copyProperties(takerRecordBean, takerRecord);

        takerRecord.setAdminCompanyId(adminUser.getAdminCompanyId());
        takerRecord.setCreateName(adminUser.getNickName());
        takerRecord.setUpdateName(adminUser.getNickName());
        takerRecord.setFlag(1);
        takerRecord.setCustomerName(customer.getName());
        takerRecord.setCustomerNumber(customer.getNumber());

        takerRecord.updateById();
    }
}
