package cn.com.ty.lift.enterprise.custom.service.impl;

import cn.com.ty.lift.enterprise.custom.dao.entity.PropertyCompany;
import cn.com.ty.lift.enterprise.custom.dao.entity.PropertyContact;
import cn.com.ty.lift.enterprise.custom.dao.entity.model.PropertyCompanyAndPropertyContactReq;
import cn.com.ty.lift.enterprise.custom.dao.entity.model.PropertyCompanyReq;
import cn.com.ty.lift.enterprise.custom.dao.mapper.PropertyCompanyMapper;
import cn.com.ty.lift.enterprise.custom.service.PropertyCompanyService;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * (甲方公司)客户表 服务实现类
 * </p>
 *
 * @author wang-hai-cheng
 * @since 2019-11-11
 */
@Service
@AllArgsConstructor
public class PropertyCompanyServiceImpl extends ServiceImpl<PropertyCompanyMapper, PropertyCompany> implements PropertyCompanyService {
    private final PropertyContactServiceImpl propertyContactService;

    public RestResponse propertyCompanies(PropertyCompanyReq request) {
        //根据请求参数查询客户列表
        IPage<PropertyCompany> records = this
                .page(request.getPage(), new QueryWrapper<PropertyCompany>()
                        .select("id", "mt_company_id", "name", "mailing_address", "status")
                        .eq(request.getMtCompanyId() != null, "mt_company_id", request.getMtCompanyId())
                        .ne("status", 0)
                        .and(request.getInfo() != null && !request.getInfo().equals(""), companyQueryWrapper ->
                                companyQueryWrapper
                                        .like("name", request.getInfo())
                                        .or()
                                        .like("address", request.getInfo())
                                        .or()
                                        .like("mailing_address", request.getInfo()))
                        .orderByAsc("CONVERT(name using gbk)"));
        records.getRecords().forEach(propertyCompany -> {
            if (propertyCompany.getMailingAddress() == null) {
                propertyCompany.setMailingAddress("未设置地址");
            }
        });
        return RestResponse.success(records);
    }

    @Transactional(rollbackFor = Exception.class)
    public RestResponse saveAll(PropertyCompanyAndPropertyContactReq req) {
        PropertyCompany propertyCompany = req.getPropertyCompany();
        boolean ppc = save(propertyCompany);
        if (!ppc) {
            return RestResponse.fail("保存甲方公司失败");
        }
        List<PropertyContact> propertyContacts = req.getPropertyContacts();
        propertyContacts.forEach(contact -> contact.setPpCompanyId(propertyCompany.getId()));
        boolean ppt = propertyContactService.saveBatch(propertyContacts);
        if (ppt) {
            return RestResponse.success(true);
        } else {
            //强制手动事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.fail("保存甲方联系人失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public RestResponse delete(Long id) {
        PropertyCompany byId = this.getById(id);
        if (null == byId) {
            return RestResponse.success();
        }
        if (byId.getStatus() == 2) {
            return RestResponse.success(null, "有正在服务的关联项目，无法删除");
        }
        long count = this.baseMapper.selectProjectCountForPPCompanyId(byId.getId());
        if (count > 0) {
            byId.setStatus(2);
            this.updateById(byId);
            return RestResponse.success(null, "有正在服务的关联项目，无法删除");
        }
        byId.setStatus(0);
        if (this.updateById(byId)) {
            return RestResponse.success(null, "成功");
        }
        return RestResponse.fail();
    }

    public void export(PropertyCompanyReq req, HttpServletResponse response) {
        List<PropertyCompany> companies = this.list(new QueryWrapper<PropertyCompany>()
                .select("id", "name", "mailing_address", "status")
                .eq("mt_company_id", req.getMtCompanyId())
                .ne("status", 0));
        List<List<?>> rows = new ArrayList<>();
        //设置列头
        rows.add(CollUtil.newArrayList("甲方公司id", "名称", "通讯地址", "状态"));
        companies.forEach(company -> {
            List<?> row = CollUtil.newArrayList(
                    company.getId().toString()
                    , company.getName()
                    , null != company.getMailingAddress() ? company.getMailingAddress() : "无"
                    , company.getStatus() == 1 ? "无关联项目" : "有关联项目");
            rows.add(row);
        });

        ExcelWriter writer = ExcelUtil.getWriter(true);
        //设置列宽

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + LocalDate.now().toString() + ".xlsx");
        try (ServletOutputStream out = response.getOutputStream()) {
            writer.write(rows);
            writer.autoSizeColumnAll();
            writer.flush(out, true);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}