package com.ghy.web.controller.worker;

import com.ghy.common.annotation.Log;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.enums.WorkerCertifyStatus;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ObjectUtils;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.goods.domain.DeptGoodsCategory;
import com.ghy.goods.service.DeptGoodsCategoryService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerBank;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.domain.WorkerSpecialSkill;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerBankService;
import com.ghy.worker.service.WorkerService;
import com.ghy.worker.service.WorkerSpecialSkillService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 师傅实名审核Controller
 *
 * @author clunt
 * @date 2022-07-07
 */
@Controller
@RequestMapping("/worker/certification")
public class WorkerCertificationController extends BaseController
{
    private String prefix = "worker/certification";

    @Autowired
    private IWorkerCertificationService workerCertificationService;

    @Autowired
    private WorkerSpecialSkillService workerSpecialSkillService;

    @Autowired
    private WorkerBankService workerBankService;

    @Autowired
    private ISysAreaService sysAreaService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private DeptGoodsCategoryService deptGoodsCategoryService;

    @RequiresPermissions("worker:certification:view")
    @GetMapping()
    public String certification()
    {
        return prefix + "/certification";
    }

    /**
     * 查询师傅实名审核列表
     */
    @RequiresPermissions("worker:certification:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkerCertification workerCertification)
    {
        startPage();
        if(this.getSysUser().getDept().getParentId() != 101){
            workerCertification.setDeptId(this.getSysUser().getDept().getParentId());
        }
        List<WorkerCertification> list = workerCertificationService.selectWorkerCertificationList(workerCertification);
        list.forEach(worker->{
            worker.setName(worker.getSurname() + worker.getName());
        });
        return getDataTable(list);
    }

    /**
     * 导出师傅实名审核列表
     */
    @RequiresPermissions("worker:certification:export")
    @Log(title = "师傅实名审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkerCertification workerCertification)
    {
        List<WorkerCertification> list = workerCertificationService.selectWorkerCertificationList(workerCertification);
        ExcelUtil<WorkerCertification> util = new ExcelUtil<WorkerCertification>(WorkerCertification.class);
        return util.exportExcel(list, "师傅实名审核数据");
    }

    /**
     * 新增师傅实名审核
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存师傅实名审核
     */
    @RequiresPermissions("worker:certification:add")
    @Log(title = "师傅实名审核", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WorkerCertification workerCertification)
    {
        return toAjax(workerCertificationService.insertWorkerCertification(workerCertification));
    }

    /**
     * 修改师傅实名审核
     */
    @RequiresPermissions("worker:certification:edit")
    @GetMapping("/edit/{workerCertificationId}")
    public String edit(@PathVariable("workerCertificationId") String workerCertificationId, ModelMap mmap)
    {
        WorkerCertification workerCertification = workerCertificationService.selectWorkerCertificationByWorkerCertificationId(workerCertificationId);
        mmap.put("workerCertification", workerCertification);
        return prefix + "/edit";
    }

    /**
     * 修改保存师傅实名审核
     */
    @RequiresPermissions("worker:certification:edit")
    @Log(title = "师傅实名审核", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkerCertification workerCertification)
    {
        return toAjax(workerCertificationService.updateWorkerCertification(workerCertification));
    }

    /**
     * 删除师傅实名审核
     */
    @RequiresPermissions("worker:certification:remove")
    @Log(title = "师傅实名审核", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(workerCertificationService.deleteWorkerCertificationByWorkerCertificationIds(ids));
    }

    @PostMapping("/app/add")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult appAddCertify(@RequestBody WorkerCertification request) {
        Worker worker = workerService.selectById(request.getWorkerId());
        request.setWorkerPhone(worker != null ? worker.getPhone() : null);
        // 将师傅状态设置为冻结
//        Worker worker = new Worker();
//        worker.setWorkerId(request.getWorkerId());
//        worker.setStatus(WorkerStatus.DISABLE.getCode());
//        int updateRows = workerService.updateWorker(worker);
//        Assert.isTrue(updateRows == 1, "实名认证记录新增失败");
        // 删除存在的认证记录
        workerCertificationService.deleteCertificationByWorkerId(request.getWorkerId());
        // 插入新的认证记录
        request.setStatus(WorkerCertifyStatus.AUDITING.getCode());
        int insertRows = workerCertificationService.insertWorkerCertification(request);
        Assert.isTrue(insertRows == 1, "实名认证记录新增失败");
        // 入驻特殊技能信息持久化
        workerSpecialSkillService.updateWorkerSpecialSkill(request.getWorkerId(), request.getSpecialSkills());
        return AjaxResult.success("保存成功");
    }

    @PostMapping("/app/getByWorkerId")
    @ResponseBody
    public AjaxResult getByWorkerId(@RequestBody WorkerCertification request) {
        try {
            WorkerCertification workerCertification = workerCertificationService.selectByWorkerId(request.getWorkerId());
            if (workerCertification != null) {
                List<WorkerSpecialSkill> byWorker = workerSpecialSkillService.getByWorker(request.getWorkerId());
                byWorker.forEach(workerSpecialSkill -> {
                    DeptGoodsCategory three = deptGoodsCategoryService.selectOneByGoodsCategoryId(workerSpecialSkill.getSpecialSkillId());
                    if(three != null){
                        workerSpecialSkill.setThreeDeptGoodsCategory(three);
                        DeptGoodsCategory two = deptGoodsCategoryService.selectOneByGoodsCategoryId(three.getParentCategoryId());
                        if(two != null){
                            workerSpecialSkill.setTwoDeptGoodsCategory(two);
                            DeptGoodsCategory first = deptGoodsCategoryService.selectOneByGoodsCategoryId(two.getParentCategoryId());
                            if(first != null){
                                workerSpecialSkill.setFirstDeptGoodsCategory(first);
                            }
                        }
                    }
                });
                workerCertification.setSpecialSkills(byWorker);
                if (workerCertification.getCompanyCountryId() != null) {
                    SysArea sysArea = sysAreaService.selectById(workerCertification.getCompanyCountryId());
                    workerCertification.setMergerName(sysArea.getMergerName());
                }
            }
            return AjaxResult.success(workerCertification);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(String ids,Integer status){
        try {
            int result = workerCertificationService.changeStatus(ids, status);
            if(result > 0){
                String [] idArray = ids.split(",");
                for (String id : idArray){
                    WorkerCertification workerCertification = workerCertificationService.selectWorkerCertificationByWorkerCertificationId(id);
                    // 是否绑定了银行卡
                    WorkerBank workerBank = workerBankService.getByWorkerId(workerCertification.getWorkerId(), 101L);
                    // 没有绑定了银行卡的用户
                    if(ObjectUtils.isEmpty(workerBank)){
                        return AjaxResult.success("操作成功!");
                    }
                    Worker worker = new Worker();
                    worker.setWorkerId(workerBank.getWorkerId());
                    worker.setStatus(0);
                    workerService.updateWorker(worker);
                }

                return AjaxResult.success("操作成功!");
            }else {
                return AjaxResult.warn("操作失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return AjaxResult.error("操作失败!");
        }
    }
}
