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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.CompanyInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlantForm;
import com.sifang.modules.sunshine.SystemSetting.utils.ComUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.order.utils.Apiutils;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
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 org.apache.commons.lang3.StringUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公司资料设置---平台端维护 service
 */
@Service
public class CompanyInformationService extends BaseService {
    @Autowired
    private CompanyInformationDao companyInformationDao;
    @Autowired
    private UserDao userDao;

    /**
     * 获取公司资料设置信息
     * @return
     */
    public Record getCompanyAllData(String userId){
        Record rd = companyInformationDao.getCompanyAllData(userId);
        return rd;
    }


    /**
     * 公司收款设置中的保存
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object colectionSave(HttpServletRequest request){
        Result result = new Result();
        try {
            String id = request.getParameter("idVal");
            String openName = request.getParameter("openName");//开户名称
            String openBlank = request.getParameter("openBlank");//开户银行
            String openAccount = request.getParameter("openAccount");//汇款账号
            logger.info("公司收款设置中的保存 >>>  openName {},openBlank {} ,openAccount {} ,id {} ,uderId: {}",openName,openBlank,openAccount,id,UserUtils.getUser().getId());
            if(StringUtils.isNotBlank(id)){
                CrmPlantForm crmPlantForm = companyInformationDao.get(id);
                logger.info("获取CrmPlantForm平台信息表对象:"+crmPlantForm.getAccountName()+",获取时间:"+ DateUtils.getDateTime());
                if(crmPlantForm !=null){
                    Map<String,String> map = ComUtils.getIpName();
                    crmPlantForm.setAccountName(openName);
                    crmPlantForm.setBank_of_deposit(openBlank);
                    crmPlantForm.setOpen_account(openAccount);
                  /*  crmPlantForm.setUpdate_time(new Date());*/
                    crmPlantForm.setRemarks(map.get("name")+" : "+ map.get("ip"));
                    companyInformationDao.save(crmPlantForm);//执行保存操作
                  //  logger.info("执行保存成功:"+crmPlantForm+",获取时间:"+ DateUtils.getDateTime());
                }
            }
            result.setCode("200");
        }catch (Exception e){
            result.setCode("205");
            logger.info("输出异常信息:"+e+",time:"+DateUtils.getDateTime());
        }
        return result;
    }

    /**
     * 修改密码中的保存
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object updatePassword(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try{
            String oldPassword = request.getParameter("originalPassword");//用户输入的原密码
            String currentPassword = request.getParameter("currentPassword");//新密码
            User user = UserUtils.getUser();
            String id = user.getId();
            User userNew = userDao.getById(id);
            String userPassword = userNew.getPassword();//数据库里加密的原密码
            logger.info("获取user表中对应的id:"+id+",获取user表中对应记录的加密密码:"+userPassword);
            if(StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(currentPassword)){
                String oldpass = RandomUtil.entryptPassword(oldPassword);//用户输入的原密码进行加密
                if(userPassword.equals(oldpass)){//校验原密码是否匹配
                    userNew.setPassword(RandomUtil.entryptPassword(currentPassword));
                    userDao.save(userNew);
                    map.put("code","200");//成功
                    logger.info("校验用户输入的密码和数据库对应记录的密码相同"+" "+",校验用户输入的密码:"+oldpass+",数据库对应记录的密码:"+userPassword);
                }else{
                    map.put("code","505");//校验原密码不匹配
                    logger.info("校验用户输入的密码和数据库对应记录的密码不匹配"+" "+",校验用户输入的密码:"+oldpass+",数据库对应记录的密码:"+userPassword);
                }
            }
        }catch (Exception e){
            map.put("code","205");//失败
        }
        return map;
    }

    /**
     * 修改资料保存
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object getSave(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        try{
            String id = request.getParameter("idVal");//id
            String corporator = request.getParameter("corporator");//法人代表
            String contacts = request.getParameter("contacts");//联系人
            String mobile = request.getParameter("mobile");//联系电话
            String province = request.getParameter("province");//省
            String city = request.getParameter("city");//市
            String area = request.getParameter("area");//区
            String detailAddress = request.getParameter("detailAddress");//详细地址
            String imgs = request.getParameter("imgs");//营业执照
            User user = UserUtils.getUser();
            String userId = user.getId();
            User userNew = userDao.getById(userId);
            if(StringUtils.isNotBlank(id)){
                CrmPlantForm crmPlantForm = companyInformationDao.get(id);
                logger.info("获取对象信息CrmPlantForm crmPlantForm:"+crmPlantForm+",time:"+DateUtils.getDateTime());
                if(crmPlantForm != null){
                   /* crmPlantForm.setCorporator(corporator);*/
                    crmPlantForm.setContacts(contacts);
                    crmPlantForm.setMobile(mobile);
                    crmPlantForm.setProvince(province);
                    crmPlantForm.setCity(city);
                    crmPlantForm.setArea(area);
                    crmPlantForm.setAddress(detailAddress);
                /*    crmPlantForm.setLicense_imgs(imgs);*/
                    String datailsAddress = crmPlantForm.getProvince()+crmPlantForm.getCity()+crmPlantForm.getArea()+crmPlantForm.getAddress();
                    double[] dals = Apiutils.addressToGPS(datailsAddress);
                    if(dals != null){
                        crmPlantForm.setLnglat(Double.toString(dals[0])+","+Double.toString(dals[1]));
                    }
                   /* crmPlantForm.setUpdate_time(new Date());*/
                    companyInformationDao.save(crmPlantForm);
                    userNew.setMobile(mobile);
                    userDao.save(userNew);
                    logger.info("数据保存成功:"+crmPlantForm+",time:"+DateUtils.getDateTime());
                }
            }
            map.put("code","200");
        }catch (Exception e){
            map.put("code","205");
            logger.info("输出异常信息状态码:"+"205"+",输出异常信息:"+e);
        }
        return map;
    }


    /**
     * 获取市
     */
    public List<Record> getCitysByProId(){
        String sql = "SELECT c.CityID,c.CityName,c.ProvinceId,c.AreaCode FROM s_city c ";
        return Db.find(sql);
    }

    /**
     * 获取区县
     */
    public static List<Record> getAreaByCityId(){
        String sql = "SELECT d.DistrictID,d.DistrictName FROM s_district d ";
        return Db.find(sql);
    }
/**
 * 平台设置支付宝及微信收款码
 */
public String saveImg(String img,String type){
    User user=UserUtils.getUser();
  /*  if(!User.DEL_FLAG_DELETE.equals(user.getUserType())){
        return "400"; //非平台管理员不可操作
    }*/
    try {
        CrmPlantForm crmPlantForm=companyInformationDao.getPlantForm();
        if(crmPlantForm!=null){
            if("1".equals(type)){
                crmPlantForm.setAlipayImgs(img);
            }else if("2".equals(type)){
                crmPlantForm.setWxImgs(img);
            }else if("3".equals(type)){
                crmPlantForm.setOtherImgs(img);
            }
            companyInformationDao.save(crmPlantForm);
        }
        return "200";
    }catch (Exception e){
        e.printStackTrace();
        return "203";
    }


}

}
