package com.testor.module.partner.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.constant.DefaultRule;
import com.testor.common.util.FileUtil;
import com.testor.module.partner.model.domain.TPartnerStaff;
import com.testor.module.partner.model.dto.TPartnerStaffDTO;
import com.testor.module.partner.model.dto.TPartnerStaffDelParam;
import com.testor.module.partner.model.dto.TPartnerStaffParam;
import com.testor.module.partner.model.vo.OrganizationPersonnelVO;
import com.testor.module.partner.model.vo.PartnerStaffDetailVO;
import com.testor.module.partner.service.TPartnerStaffService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.supers.SuperModel;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 相关方机构员工Controller
 *
 * @author testor-framework
 * @date 2022-06-01 14:18:06
 */
@RestController
@RequestMapping("/partner/partnerStaff")
@Api(value = "TPartnerStaff", tags = "相关方机构员工")
@Slf4j
public class TPartnerStaffController extends SuperController {
    @Autowired
    private TPartnerStaffService tPartnerStaffService;

    @Autowired
    private SysRuleService sysRuleService;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @Value("${ureport.path}")
    private String path;

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "获取组织机构及人员", notes = "Add TPartnerStaff")
    @GetMapping(value = "/getOrganizationPersonnel")
    public BaseResponse<Map<String, List<OrganizationPersonnelVO>>> getOrganizationPersonnel() {
        Map<String, List<OrganizationPersonnelVO>> a = tPartnerStaffService.getOrganizationPersonnel();
        BaseResponse<Map<String, List<OrganizationPersonnelVO>>> mapBaseResponse = new BaseResponse<>();
        mapBaseResponse.setData(a);
        return mapBaseResponse;
    }


    @ApiOperation(value = "新增 相关方机构员工", notes = "Add TPartnerStaff")
    @PostMapping(value = "/add")
    public BaseResponse<TPartnerStaff> addEntity(@RequestBody TPartnerStaffDTO addRequest) {
        return tPartnerStaffService.editPartnerStaff(addRequest);
    }

    @ApiOperation(value = "获取 相关方机构员工详情 ", notes = "Get TPartnerStaff By Id")
    @GetMapping(value = "/get")
    public BaseResponse<PartnerStaffDetailVO> getById(String id) {
        BaseResponse<PartnerStaffDetailVO> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            PartnerStaffDetailVO partnerStaffDetail = tPartnerStaffService.getPartnerStaffDetail(id);
            baseResponse.setData(partnerStaffDetail);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 相关方机构员工", notes = "Update TPartnerStaff By Id")
    @PutMapping(value = "/update")
    public BaseResponse<TPartnerStaff> updateEntity(@RequestBody TPartnerStaffDTO updateRequest) {
        return tPartnerStaffService.editPartnerStaff(updateRequest);
    }

    @ApiOperation(value = "删除 相关方机构员工", notes = "delete TPartnerStaff By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TPartnerStaffDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            boolean update = false;
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TPartnerStaff data = new TPartnerStaff();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tPartnerStaffService.updateById(data);
            if (result) {
                SysUser sysUser = new SysUser();
                sysUser.setUserId(deleteRequest.getSysUserId());
                sysUser.setStatus(BizConstants.STATUS_DELETE);
                update = sysUserService.updateById(sysUser);
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(update)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "导出列表")
    @GetMapping(value = "/exportPartnerStaff")
    public BaseResponse<BizGeneralResponse> exportPartnerStaff(HttpServletRequest request, TPartnerStaffParam tPartnerStaffParam) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        tPartnerStaffService.exportPartnerStaff(response, tPartnerStaffParam);
        return baseResponse;
    }

    @ApiOperation(value = "导入人员信息")
    @PostMapping(value = "/importPersonnel")
    public BaseResponse importPersonnel(@RequestParam("file") MultipartFile file) throws IOException {
        BaseResponse<String> baseResponse = tPartnerStaffService.importPersonnel(file);
        return baseResponse;
    }


    /*@ApiOperation(value = "批量删除相关方机构员工", notes = "delete TPartnerStaff by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TPartnerStaffDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            *//* 批量删除 *//*
            List<TPartnerStaff> tPartnerStaffList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TPartnerStaff data = new TPartnerStaff();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tPartnerStaffList.add(data);
            }
            boolean result = tPartnerStaffService.updateBatchById(tPartnerStaffList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }*/

    @ApiOperation(value = "获取 相关方机构员工 分页列表 ", notes = "List TPartnerStaff with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<PartnerStaffDetailVO>> listEntity(@RequestBody TPartnerStaffParam param) {
        BaseResponse<BaseResponseList<PartnerStaffDetailVO>> baseResponse = new BaseResponse<>();

        if (param.getCondOrgIdList() == null || param.getCondOrgIdList().size() == 0) {
            String orgId = ContextUtils.getLoginUser().getOrgId();
            List<String> list = new ArrayList<>();
            list.add(orgId);
            param.setCondOrgIdList(list);
        }

        IPage<PartnerStaffDetailVO> resultList = tPartnerStaffService.listByPage(param);
        BaseResponseList<PartnerStaffDetailVO> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 相关方机构员工列表 根据相关方ids ", notes = "List TPartnerStaff with page")
    @PostMapping(value = "/listEntityByIds")
    public BaseResponse<List<TPartnerStaff>> listEntityByIds(@RequestBody List<String> ids) {
        BaseResponse<List<TPartnerStaff>> listBaseResponse = new BaseResponse<>();
        String orgId = ContextUtils.getLoginUser().getOrgId();
        if (ObjectUtil.isNotEmpty(ids)) {
            List<TPartnerStaff> list = tPartnerStaffService.list(
                    new LambdaQueryWrapper<TPartnerStaff>()
                            .eq(SuperModel::getStatus, "0").in(!CollectionUtils.isEmpty(ids),TPartnerStaff::getPartnerId, ids
                            ).eq(TPartnerStaff::getOrgId,orgId));
            listBaseResponse.setData(list);
        }

        return listBaseResponse;
    }


    /*@ApiOperation(value = "获取 相关方机构员工 列表", notes = "List TPartnerStaff all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TPartnerStaff>> listAllEntity(TPartnerStaffParam param) {
        BaseResponse<BaseResponseList<TPartnerStaff>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TPartnerStaff> queryWrapper = this.createQuery(param);
        List<TPartnerStaff> resultList = tPartnerStaffService.list(queryWrapper);
        BaseResponseList<TPartnerStaff> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }*/

    @ApiOperation(value = "导出相关方人员", notes = "")
    @PostMapping("/exportPartnerStaff")
    public void exportPartnerStaff(@RequestBody List<String> ids) throws Exception {
        String url = this.path + "/ureport/excel?_u=file:partnerStaff.ureport.xml";

        if (null != ids && ids.size() > 0) {
            url = url + "&ids=" + ids;
        }

        String fileName = "相关方人员.xlsx";
        FileUtil.downloadHttpFile(url, request, response, fileName);
    }

    @ApiOperation(value = "批量导入相关方人员", notes = "")
    @GetMapping("/importPartnerStaff")
    public BaseResponse<String> importPartnerOrg(@RequestParam("file") MultipartFile file) throws Exception {
        return tPartnerStaffService.addReportByExcel(file);
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TPartnerStaff> createQuery(TPartnerStaffParam queryParam) {
        QueryWrapper<TPartnerStaff> queryWrapper = new QueryWrapper<>();

        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
        if (StringUtils.isNotEmpty(rule)) {
            queryWrapper.apply(rule);
        }

        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TPartnerStaff.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getPartnerId())) {
            queryWrapper.eq(TPartnerStaff.PARTNER_ID, queryParam.getPartnerId());
        }
        if (StringHelper.isNotEmpty(queryParam.getName())) {
            queryWrapper.like(TPartnerStaff.NAME, queryParam.getName());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getSex())) {
            queryWrapper.eq(TPartnerStaff.SEX, queryParam.getSex());
        }
        if (StringHelper.isNotEmpty(queryParam.getWorkType())) {
            queryWrapper.eq(TPartnerStaff.WORK_TYPE, queryParam.getWorkType());
        }
        if (StringHelper.isNotEmpty(queryParam.getIdcard())) {
            queryWrapper.eq(TPartnerStaff.IDCARD, queryParam.getIdcard());
        }
        if (StringHelper.isNotEmpty(queryParam.getPhone())) {
            queryWrapper.eq(TPartnerStaff.PHONE, queryParam.getPhone());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getCertificateStatus())) {
            queryWrapper.eq(TPartnerStaff.CERTIFICATE_STATUS, queryParam.getCertificateStatus());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getAge())) {
            queryWrapper.eq(TPartnerStaff.AGE, queryParam.getAge());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TPartnerStaff.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TPartnerStaff.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TPartnerStaff.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TPartnerStaff.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
