package com.org.hktshop.service.System;

import com.aliyun.oss.OSSClient;
import com.org.hktshop.Interface.system.IHktHelperCenterService;
import com.org.hktshop.Interface.system.IHktSysHelpsCategoryService;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.admin.HktAdmin;
import com.org.hktshop.entity.system.HktSysHelpes;
import com.org.hktshop.entity.system.HktSysHelpsCategory;
import com.org.hktshop.properties.AliyunOSSProperties;
import com.org.hktshop.service.aliyun.AliyunOssService;
import com.org.hktshop.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class HktHelperCenterServiceImpl extends BaseService<HktSysHelpes> implements IHktHelperCenterService {

    @Autowired
    MongoHelper<HktSysHelpes> mongoHelper;
    @Autowired
    IHktSysHelpsCategoryService categoryService;
    @Autowired
    AliyunOSSProperties aliyunOSSProperties;
    @Autowired
    AliyunOssService aliyunOssService;

    @Override
    public Page<HktSysHelpes> queryPage(HktSysHelpes hktSysHelpes) {
        Page<HktSysHelpes> page = mongoHelper.findPage(hktSysHelpes, HktSysHelpes.class);
        List<HktSysHelpsCategory> list = categoryService.queryLists(new HktSysHelpsCategory());
        for (HktSysHelpes helpes : page.getRecords()) {
            for (HktSysHelpsCategory category : list) {
                if (category.getId().equals(helpes.getCategoryId())) {
                    helpes.setCategoryName(category.getName());
                    break;
                }
            }
        }
        return page;
    }

    @Override
    public List<HktSysHelpes> queryLists(HktSysHelpes hktSysHelpes) {
        List<HktSysHelpes> list = mongoHelper.find(hktSysHelpes, HktSysHelpes.class);
        if (list.isEmpty()) {
            try {
                list = queryList(new HktSysHelpes());
                for (HktSysHelpes helpes1 : list) {
                    mongoHelper.save(helpes1);
                }
                list = mongoHelper.find(hktSysHelpes, HktSysHelpes.class);
            } catch (Exception ex) {
                //异常怎么处理
            }
        }

        List<HktSysHelpsCategory> categories = categoryService.queryLists(new HktSysHelpsCategory());
        for (HktSysHelpes helpes : list) {
            for (HktSysHelpsCategory category : categories) {
                if (category.getId().equals(helpes.getCategoryId())) {
                    helpes.setCategoryName(category.getName());
                    break;
                }
            }
        }
        return list;
    }

    @Override
    public HktSysHelpes queryHelper(HktSysHelpes hktSysHelpes) {
        HktSysHelpes helpes = mongoHelper.findOne(hktSysHelpes, HktSysHelpes.class);
        if (helpes == null) return null;

        if (!StringUtils.isNull(helpes.getContent())) {
            OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
            helpes.setContent(aliyunOssService.getTxtMsg(ossClient, helpes.getContent()));
        }
        if (!StringUtils.isNull(helpes.getHcontent())) {
            OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
            helpes.setHcontent(aliyunOssService.getTxtMsg(ossClient, helpes.getHcontent()));
        }

        List<HktSysHelpsCategory> list = categoryService.queryLists(new HktSysHelpsCategory());

        for (HktSysHelpsCategory category : list) {
            if (category.getId().equals(helpes.getCategoryId())) {
                helpes.setCategoryName(category.getName());
                break;
            }
        }
        return helpes;
    }

    /****
     *
     * @param admin
     * @param hktSysHelpes
     * @return
     */
    @Override
    public Ret updateHktHelpCenter(HktAdmin admin, HktSysHelpes hktSysHelpes) throws UnsupportedEncodingException {
        Ret ret = Ret.create();

        if (StringUtils.isNull(hktSysHelpes.getId())) {
            //新增
            hktSysHelpes.setCreateTime(DateUtil.getDateTime());
            hktSysHelpes.setModifyTime(DateUtil.getDateTime());

            HktSysHelpsCategory find = new HktSysHelpsCategory();
            find.setId(hktSysHelpes.getCategoryId());
            HktSysHelpsCategory category = categoryService.queryCategory(find);
            if (category == null) return Ret.create().setFail().setMsg("新增失败");
            category.setHelpCount(MathUtil.addInt(category.getHelpCount(), 1));

            if (!StringUtils.isNull(hktSysHelpes.getContent())) {
                OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                String url = aliyunOssService.uploadForStr(ossClient, hktSysHelpes.getContent(), "helpInfo/" + System.currentTimeMillis() + ".html");
                hktSysHelpes.setContent(url);
            }
            if (!StringUtils.isNull(hktSysHelpes.getHcontent())) {
                OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                String url = aliyunOssService.uploadForStr(ossClient, hktSysHelpes.getHcontent(), "helpInfo/" + System.currentTimeMillis() + ".html");
                hktSysHelpes.setHcontent(url);
            }

            List<String> sql = new ArrayList<>();
            sql.add(ExecSqlLib.GetUpdateSql(category));
            sql.add(ExecSqlLib.GetInsertSql(hktSysHelpes));

            if (this.baseJdbcDao.executeTransaction(sql)) {
                List<HktSysHelpes> list = queryList(hktSysHelpes);
                for (HktSysHelpes helps : list) {
                    mongoHelper.save(helps);
                }
                MongoHelper<HktSysHelpsCategory> hktSysHelpsCategoryMongoHelper = new MongoHelper<>();
                hktSysHelpsCategoryMongoHelper.mongoUpdate(category.getId(), category, HktSysHelpsCategory.class);
                ret.setOk();
            } else {
                ret.setFail();
            }
        } else {
            //修改
            HktSysHelpes helpes = new HktSysHelpes();
            helpes.setId(hktSysHelpes.getId());
            HktSysHelpes find = mongoHelper.findOne(helpes, HktSysHelpes.class);
            if (find == null) return ret.setFail().setMsg("当前对象不存在");

            List<String> sql = new ArrayList<>();
            HktSysHelpsCategory oldCategory = null;
            HktSysHelpsCategory newCategory = null;
            if (!find.getCategoryId().equals(hktSysHelpes.getCategoryId())) {
                //旧值
                HktSysHelpsCategory findcategory = new HktSysHelpsCategory();
                findcategory.setId(hktSysHelpes.getCategoryId());
                oldCategory = categoryService.queryCategory(findcategory);
                if (oldCategory == null) return Ret.create().setFail().setMsg("修改失败");
                oldCategory.setHelpCount(MathUtil.addInt(oldCategory.getHelpCount(), -1));
                sql.add(ExecSqlLib.GetUpdateSql(oldCategory));
                //新值
                findcategory = new HktSysHelpsCategory();
                findcategory.setId(find.getCategoryId());
                newCategory = categoryService.queryCategory(findcategory);
                if (newCategory == null) return Ret.create().setFail().setMsg("修改失败");
                newCategory.setHelpCount(MathUtil.addInt(newCategory.getHelpCount(), 1));
                sql.add(ExecSqlLib.GetUpdateSql(newCategory));
            }

            if (!StringUtils.isNull(hktSysHelpes.getTitle())) find.setTitle(hktSysHelpes.getTitle());
            if (!StringUtils.isNull(hktSysHelpes.getCategoryId())) find.setCategoryId(hktSysHelpes.getCategoryId());
            if (!StringUtils.isNull(hktSysHelpes.getIsTop())) find.setIsTop(hktSysHelpes.getIsTop());
            if (!StringUtils.isNull(hktSysHelpes.getContent())) {
                if (!StringUtils.isNull(hktSysHelpes.getContent())) {
                    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                    aliyunOssService.uploadForStr(ossClient, hktSysHelpes.getContent(), find.getContent().substring(find.getContent().indexOf(aliyunOSSProperties.getFileHost()) + aliyunOSSProperties.getFileHost().length() + 1));
                }
            }
            if (!StringUtils.isNull(hktSysHelpes.getHcontent())) {
                if (!StringUtils.isNull(hktSysHelpes.getHcontent())) {
                    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                    aliyunOssService.uploadForStr(ossClient, hktSysHelpes.getHcontent(), find.getHcontent().substring(find.getHcontent().indexOf(aliyunOSSProperties.getFileHost()) + aliyunOSSProperties.getFileHost().length() + 1));
                }
            }
            find.setModifyTime(DateUtil.getDateTime());

            sql.add(ExecSqlLib.GetUpdateSql(find));
            if (this.baseJdbcDao.executeTransaction(sql)) {
                //成功更新
                mongoHelper.mongoUpdate(find.getId(), find, HktSysHelpes.class);
                if (oldCategory != null) {
                    MongoHelper<HktSysHelpsCategory> hktSysHelpsCategoryMongoHelper = new MongoHelper<>();
                    hktSysHelpsCategoryMongoHelper.mongoUpdate(oldCategory.getId(), oldCategory, HktSysHelpsCategory.class);
                    hktSysHelpsCategoryMongoHelper.mongoUpdate(newCategory.getId(), newCategory, HktSysHelpsCategory.class);
                }
                ret.setOk();
            } else {
                ret.setFail();
            }
        }
        return ret;
    }

    @Override
    public Ret deleteHktHelpCenter(HktAdmin admin, HktSysHelpes hktSysHelpes) {

        HktSysHelpes helpes = mongoHelper.findOne(hktSysHelpes, HktSysHelpes.class);
        if (helpes == null) return Ret.create().setFail().setMsg("参数错误");

        HktSysHelpsCategory find = new HktSysHelpsCategory();
        find.setId(helpes.getCategoryId());
        HktSysHelpsCategory category = categoryService.queryCategory(find);
        if (category == null) return Ret.create().setFail().setMsg("参数错误");

        Integer count = MathUtil.addInt(category.getHelpCount(), -1);
        if (count < 0) count = 0;
        category.setHelpCount(count);
        List<String> sqls = new ArrayList<>();
        sqls.add(ExecSqlLib.GetUpdateSql(category));
        sqls.add(ExecSqlLib.GetDeleteByIdSql(hktSysHelpes.getId(), hktSysHelpes));

        if (this.baseJdbcDao.executeTransaction(sqls)) {
            mongoHelper.removeById(hktSysHelpes.getId(), HktSysHelpes.class);

            MongoHelper<HktSysHelpsCategory> hktSysHelpsCategoryMongoHelper = new MongoHelper<>();
            hktSysHelpsCategoryMongoHelper.mongoUpdate(category.getId(), category, HktSysHelpsCategory.class);

            if (!StringUtils.isNull(helpes.getContent())) {
                OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                aliyunOssService.deleteFile(ossClient, helpes.getContent().substring(helpes.getContent().indexOf(aliyunOSSProperties.getFileHost())));
            }
            if (!StringUtils.isNull(helpes.getHcontent())) {
                OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
                aliyunOssService.deleteFile(ossClient, helpes.getHcontent().substring(helpes.getHcontent().indexOf(aliyunOSSProperties.getFileHost())));
            }
            return Ret.create().setOk();
        }
        return Ret.create().setFail();
    }
}
