package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.utils.Apiutils;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import com.sifang.modules.site.fittingManager.dao.SiteFittingApplyMsgDao;
import com.sifang.modules.sunshine.SystemSetting.dao.EmployeInformationDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteEmploye;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingDao;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingKeepDao;
import com.sifang.modules.sunshine.fittingManager.entity.*;
import com.sifang.modules.supply.stock.constant.MaterialConstants;
import com.sifang.modules.supply.warehouse.constant.MaterialKeepConstants;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class EmployeInformationService extends BaseService {
    @Autowired
    EmployeInformationDao employeInformationDao;
    @Autowired
    UserDao userDao;
    @Autowired
    SiteInformationDao siteInformationDao;
    @Autowired
    CrmSiteFittingApplyDao crmSiteFittingApplyDao;
    @Autowired
    CrmSiteFittingDao crmSiteFittingDao;
    @Autowired
    CrmSiteFittingKeepDao crmSiteFittingkeepDao;
    @Autowired
    SiteFittingApplyMsgDao siteFittingApplyMsgDao;
    @Autowired
    OrderDao orderDao;

    public CrmSiteEmploye getById(String id) {
        return employeInformationDao.get(id);
    }

    public void getSiteEmploye(LayuiPage page, Map<String, String> map){
        List<Record> list = employeInformationDao.getSiteEmploye(page,map);
        Long count = employeInformationDao.getCount(map);
        page.setCount(count);
        page.setData(list);
    }

    /**
     * 保存工程师
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveEmploye(Map<String,String> map){
        Result result = new Result();
        try{
            String id = map.get("id") !=null ? map.get("id").toString() : "";
            String name = map.get("name") !=null ? map.get("name").toString() : "";
            String loginName = map.get("loginName") !=null ? map.get("loginName").toString() : "";
            String password = map.get("password") !=null ? map.get("password").toString() : "";
            String siteId = map.get("site") !=null ? map.get("site").toString() : "";
            String mobile = map.get("mobile") !=null ? map.get("mobile").toString() : "";
            String years = map.get("years") !=null ? map.get("years").toString() : "";
            String imgs = map.get("imgs") !=null ? map.get("imgs").toString() : "";
            List<Record> list = employeInformationDao.getEmpByName(name,siteId);
            CrmSiteEmploye emp = getById(id);
            if (emp==null) {
                if (list.size()>0) {
                    result.setCode("203");
                    return result;
                }
            }else{
                if (!emp.getName().equals(name)) {
                    if (list.size()>0) {
                        result.setCode("203");
                        return result;
                    }
                }
            }
            if(emp != null){
                User user = userDao.get(emp.getUserId());
                if (user==null) {
                    if(siteInformationDao.getExistsLoginName(loginName)){
                        result.setCode("201");
                        return result;
                    }
                    user = new User();
                    user.setCreateBy(UserUtils.getUser().getId());
                    user.setUserType("5");
                }
                if (siteInformationDao.getExistsLoginNameNew(user.getId(),loginName)) {
                    result.setCode("201");
                    return result;
                }
                user.setLoginName(loginName);
                if (!password.equals("default")) {
                    if (!user.getPassword().equals(password)) {
                        user.setPassword(RandomUtil.entryptPassword(password));
                    }
                }
                user.setMobile(mobile);
                userDao.save(user);
                emp.setName(name);
                emp.setMobile(mobile);
                emp.setLicenseImg(imgs);
                emp.setYears(years);
                employeInformationDao.save(emp);
                logger.info("保存Crmsite表数据成功："+emp+",saveTime:"+ DateUtils.getDateTime());
                result.setCode("200");
            } else{
                if(siteInformationDao.getExistsLoginName(loginName)){
                    result.setCode("201");
                    return result;
                }
                User user = new User();
                user.setCreateBy(UserUtils.getUser().getId());
                user.setUserType("5");
                user.setCreateType(1);
                user.setLoginName(loginName);
                user.setPassword(RandomUtil.entryptPassword(password));
                userDao.save(user);
                emp = new CrmSiteEmploye();
                emp.setCreateBy(UserUtils.getUser().getId());
                emp.setName(name);
                emp.setMobile(mobile);
                emp.setSiteId(siteId);
                emp.setLicenseImg(imgs);
                emp.setYears(years);
                emp.setUserId(user.getId());
                emp.setUpdateTime(new Date());
                employeInformationDao.save(emp);
                logger.info("保存CrmSiteOrderDefaultAddress表数据成功："+emp+",saveTime:"+ DateUtils.getDateTime());
                result.setCode("200");
            }
        }catch (Exception e){
            result.setCode("205");
            logger.info("返回异常信息:"+e+",saveTime:"+ DateUtils.getDateTime());
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result deleteEmploye(String id){
            try{
                if(StringUtil.isNotBlank(id)){
                    List<Record> list = siteInformationDao.getEmployeorder(id);
                    if (list.size()>0) {
                        return Result.fail("501" ,"该工程师有未完成工单，无法删除。");
                    }
                    CrmSiteEmploye emp = getById(id);
                    emp.setStatus("1");
                    emp.setUpdateTime(new Date());
                    employeInformationDao.save(emp);
                    if (emp.getUserId()!=null) {
                        User user = userDao.getById(emp.getUserId());
                        if (user!=null) {
                            user.setStatus("1");
                            user.setUpdateTime(new Date());
                            userDao.save(user);
                        }
                    }
                }
        }catch(Exception e){
            e.printStackTrace();
            return Result.fail("504","删除失败");
        }
        return Result.ok();
    }

    public void noAuditList(LayuiPage page, Map<String, String> map){
        List<Record> list = employeInformationDao.getNoAuditList(page,map);
        Long count = employeInformationDao.getNoAuditCount(map);
        page.setCount(count);
        page.setData(list);
    }

    public void auditedList(LayuiPage page, Map<String, String> map){
        List<Record> list = employeInformationDao.getAuditedList(page,map);
        Long count = employeInformationDao.getAuditedCount(map);
        page.setCount(count);
        page.setData(list);
    }

    @Transactional(rollbackFor=Exception.class)
    public Result adoptApply(String id,String fittingAuditNum,String oldFittingFlag,String factoryMarks){
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmSiteFittingApply apply = crmSiteFittingApplyDao.get(id);
        if(!MaterialConstants.APPLY_STATUS_ZERO.equals(apply.getStatus())){
            return Result.fail("401","该备件申请不满足审核条件，已审核或者已取消");
        }
        CrmSiteFitting fitting = crmSiteFittingDao.get(apply.getFittingId());
        BigDecimal warning = fitting.getWarning().subtract(new BigDecimal(fittingAuditNum));
        if (warning.intValue()<0) {
            return Result.fail("402","该备件库存不足");
        }
        //修改备件库存
        fitting.setWarning(warning);
        fitting.setNewestKeepTime(new Date());
        fitting.setRefundOldFlag(oldFittingFlag);
        crmSiteFittingDao.save(fitting);
        //修改备件申请记录
        apply.setStatus(MaterialConstants.APPLY_STATUS_ONE);
        apply.setFittingAuditNum(new BigDecimal(fittingAuditNum));
        apply.setOldFittingFlag(oldFittingFlag);
        apply.setAuditMarks(factoryMarks);
        apply.setAuditTime(new Date());
        apply.setUpdateName(name);
        apply.setUpdateTime(new Date());
        apply.setAuditor(name);
        apply.setAuditorId(user.getId());
        crmSiteFittingApplyDao.save(apply);
        //添加入库明细记录
        CrmSiteFittingkeep keep = new CrmSiteFittingkeep();
        keep.setNumber(CrmUtils.no());
        keep.setType(MaterialKeepConstants.IN);
        keep.setFittingId(fitting.getId());
        keep.setFittingCode(fitting.getCode());
        keep.setFittingName(fitting.getName());
        keep.setAmount(new BigDecimal(fittingAuditNum));
        keep.setApplicant(apply.getEmployeName());
        keep.setConfirmor(name);
        keep.setSiteId(CrmUtils.getSiteId(user));
        keep.setCreateBy(user.getId());
        keep.setRelateRecordId(apply.getId());
        crmSiteFittingkeepDao.save(keep);
        //申请操作记录表修改记录
        SiteFittingApplyMsg msg = siteFittingApplyMsgDao.findByApplyId(apply.getId());
        if(msg == null){
            msg = new SiteFittingApplyMsg();
            msg.setFittingApplyId(id);
            msg.setSiteId(apply.getSiteId());
        }
        ComplaintReply tamd = new ComplaintReply();
        tamd.setT(DateUtils.getDateTime());
        tamd.setP(name);
        tamd.setC(name + " 审核 - 工程师备件申请审核通过;");
        String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
        msg.setMessage(strmsg);
        siteFittingApplyMsgDao.save(msg);
        return Result.ok();
    }

    @Transactional(rollbackFor=Exception.class)
    public Result refuseFitting(String id,String refuseReason,String oldFittingFlag,String factoryMarks){
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmSiteFittingApply apply = crmSiteFittingApplyDao.get(id);
        if(!MaterialConstants.APPLY_STATUS_ZERO.equals(apply.getStatus())){
            return Result.fail("401","该备件申请不满足审核条件，已审核或者已取消");
        }
        apply.setStatus(MaterialConstants.APPLY_STATUS_FAIL);
        apply.setOldFittingFlag(oldFittingFlag);
        apply.setAuditTime(new Date());
        apply.setUpdateName(name);
        apply.setUpdateTime(new Date());
        apply.setAuditor(name);
        apply.setAuditorId(user.getId());
        apply.setRefuseReason(refuseReason);
        crmSiteFittingApplyDao.save(apply);
        //申请操作记录表修改记录
        SiteFittingApplyMsg msg = siteFittingApplyMsgDao.findByApplyId(apply.getId());
        if(msg == null){
            msg = new SiteFittingApplyMsg();
            msg.setFittingApplyId(id);
            msg.setSiteId(apply.getSiteId());
        }
        ComplaintReply tamd = new ComplaintReply();
        tamd.setT(DateUtils.getDateTime());
        tamd.setP(name);
        tamd.setC(name + " 审核 - 工程师备件申请审核未通过;");
        String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
        msg.setMessage(strmsg);
        siteFittingApplyMsgDao.save(msg);
        orderDao.updateFittingFlag(apply.getOrderId(),apply.getSiteId());
        return Result.ok();
    }

    @Transactional(rollbackFor=Exception.class)
    public String saveQrcode(String ids){
        String[] idArr = ids.split(",");
        try {
            for (int i = 0; i < idArr.length; i++) {
                CrmSiteEmploye employe = employeInformationDao.get(idArr[i]);
                if (employe.getQrcode() == null) {
                    employe.setQrcode("0");
                    employe.setUpdateTime(new Date());
                    employeInformationDao.save(employe);
                } else {
                    if (employe.getQrcode().equals("0")) {
                        return "402";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "401";
        }
        return "200";
    }

}
