package com.yunfeiyun.agmp.fms.controller;

import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.page.TableDataInfo;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.poi.ExcelUtil;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.fms.domain.TssSourceEnvironment;
import com.yunfeiyun.agmp.fms.domain.TssSourceinfo;
import com.yunfeiyun.agmp.fms.domain.TssSourceperiod;
import com.yunfeiyun.agmp.fms.domain.reqvo.AddTssSourceinfoReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssSourceinfoListResVo;
import com.yunfeiyun.agmp.fms.service.ITssSourceEnvironmentService;
import com.yunfeiyun.agmp.fms.service.ITssSourceinfoService;
import com.yunfeiyun.agmp.fms.service.ITssSourceperiodService;
import com.yunfeiyun.agmp.fms.service.IWmsFinishgoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 溯源信息Controller
 * 
 * @author 杨晓辉
 * @date 2023-06-25
 */
@RestController
@RequestMapping("/tss/sourceinfo")
public class TssSourceinfoController extends BaseController
{
    @Autowired
    private ITssSourceinfoService tssSourceinfoService;
    @Autowired
    private ITssSourceperiodService tssSourceperiodService;
    @Autowired
    private IWmsFinishgoodsService wmsFinishgoodsService;
    @Autowired
    private ResManager resManager;
    @Autowired
    private ITssSourceEnvironmentService tssSourceEnvironmentService;

    /**
     * 查询溯源信息列表
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(TssSourceinfo tssSourceinfo)
    {
        startPage();
        List<TssSourceinfoListResVo> list = tssSourceinfoService.selectTssSourceinfoList(tssSourceinfo);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:select:list')")
    @GetMapping("/select/list")
    public TableDataInfo selectList(TssSourceinfo tssSourceinfo)
    {
        List<TssSourceinfoListResVo> list = tssSourceinfoService.selectTssSourceinfoList(tssSourceinfo);
        return getDataTable(list);
    }

    /**
     * 导出溯源信息列表
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:export')")
    @Log(title = "溯源信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TssSourceinfo tssSourceinfo)
    {
        List<TssSourceinfoListResVo> list = tssSourceinfoService.selectTssSourceinfoList(tssSourceinfo);
        ExcelUtil<TssSourceinfoListResVo> util = new ExcelUtil<TssSourceinfoListResVo>(TssSourceinfoListResVo.class);
        util.exportExcel(response, list, "溯源信息数据");
    }

    /**
     * 获取溯源信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:info')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(@RequestParam("sourceinfoId") String sourceinfoId) {
        TssSourceinfo tssSourceinfo = tssSourceinfoService.selectTssSourceinfoBySourceinfoId(sourceinfoId);
        TssSourceinfoListResVo resVo = new TssSourceinfoListResVo();
        BeanUtils.copyProperties(tssSourceinfo, resVo);

        List<SysRes> resList1 = resManager.queryRes(sourceinfoId, ResConstants.BizType.SOURCE_INFO_AVATAR, ResConstants.mediaType.IMG);
        List<SysRes> resList2 = resManager.queryRes(sourceinfoId, ResConstants.BizType.SOURCE_INFO_QUALITY, ResConstants.mediaType.IMG);
        List<SysRes> resList3 = resManager.queryRes(sourceinfoId, ResConstants.BizType.SOURCE_INFO_FIGURE.getKey());
        resVo.setAvatarPreview(getResUrl(resList1));
        resVo.setAvatarResIds(getResIds(resList1));
        resVo.setQualityPreview(getResUrl(resList2));
        resVo.setQualityResIds(getResIds(resList2));
        resVo.setFigurePreview(getResUrl(resList3));
        resVo.setFigureResIds(getResIds(resList3));

        TssSourceperiod tssSourceperiod = new TssSourceperiod();
        tssSourceperiod.setSourceinfoId(sourceinfoId);
        tssSourceperiod.setSourceperiodParentid("0");
        List<TssSourceperiod> tssSourceperiods = tssSourceperiodService.selectTssSourceperiodList(tssSourceperiod);
        for (TssSourceperiod sourceperiod : tssSourceperiods) {
            List<SysRes> resList4 = resManager.queryRes(sourceperiod.getSourceperiodId(), ResConstants.BizType.SOURCE_INFO_PERIOD, ResConstants.mediaType.IMG);
            sourceperiod.setPeriodResIds(getResIds(resList4));
            sourceperiod.setPeriodPreview(getResUrl(resList4));

            TssSourceperiod childReqVo = new TssSourceperiod();
            childReqVo.setSourceinfoId(sourceinfoId);
            childReqVo.setSourceperiodParentid(sourceperiod.getSourceperiodId());
            List<TssSourceperiod> sourceperiods = tssSourceperiodService.selectTssSourceperiodList(childReqVo);
            for (TssSourceperiod sourceperiod1 : sourceperiods) {
                List<SysRes> resList5 = resManager.queryRes(sourceperiod1.getSourceperiodId(), ResConstants.BizType.SOURCE_INFO_PERIOD, ResConstants.mediaType.IMG);
                sourceperiod1.setPeriodResIds(getResIds(resList5));
                sourceperiod1.setPeriodPreview(getResUrl(resList5));
            }
            sourceperiod.setTssSourceperiods(sourceperiods);
        }
        resVo.setTssSourceperiods(tssSourceperiods);

        //溯源生长环境信息查询 selectTssSourceEnvironmentList
        TssSourceEnvironment tssSourceEnvironment = new TssSourceEnvironment();
        tssSourceEnvironment.setSourceinfoId(sourceinfoId);
        List<TssSourceEnvironment> tssSourceEnvironments = tssSourceEnvironmentService.selectTssSourceEnvironmentList(tssSourceEnvironment);
        for(TssSourceEnvironment tssSourceEnvironment1 : tssSourceEnvironments){
            List<SysRes> resList5 = resManager.queryRes(tssSourceEnvironment1.getSourceEnvironmentId(), ResConstants.BizType.SOURCE_INFO_ENVIRONMENT, ResConstants.mediaType.IMG);
            tssSourceEnvironment1.setEnvironmentResIds(getResIds(resList5));
            tssSourceEnvironment1.setEnvironmentPreviews(getResUrl(resList5));
        }
        resVo.setTssSourceEnvironments(tssSourceEnvironments);

        return success(resVo);
    }

    /**
     * 新增溯源信息
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:add')")
    @Log(title = "溯源信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody AddTssSourceinfoReqVo reqVo)
    {
        return tssSourceinfoService.insertTssSourceinfo(reqVo);
    }

    /**
     * 修改溯源信息
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:edit')")
    @Log(title = "溯源信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody AddTssSourceinfoReqVo reqVo)
    {
        return tssSourceinfoService.updateTssSourceinfo(reqVo);
    }

    /**
     * 删除溯源信息
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:delete')")
    @Log(title = "溯源信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete")
    public AjaxResult remove(@RequestParam String[] sourceinfoIds)
    {
        //查询是否被产品绑定
        for (String sourceinfoId : sourceinfoIds) {
            int count = wmsFinishgoodsService.selectCount(sourceinfoId);
            if (count > 0) {
                return AjaxResult.error(ErrorCode.DEL_CURNODE_ERROR.getCode(), ErrorCode.DEL_CURNODE_ERROR.getMessage());
            }
        }

        return toAjax(tssSourceinfoService.deleteTssSourceinfoBySourceinfoIds(sourceinfoIds));
    }


    /**
     * 头像信息上传
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:avatar:upload')")
    @Log(title = "头像信息上传", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar/upload")
    public AjaxResult avatarUpload(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_AVATAR, ResConstants.mediaType.IMG, "", file,getLoginUser());
            return success(sysRes);
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

    /**
     * 体检报告图片上传
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:quality:upload')")
    @Log(title = "体检报告图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/quality/upload")
    public AjaxResult qualityUpload(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_QUALITY, ResConstants.mediaType.IMG, "", file,getLoginUser());
            return success(sysRes);
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

    /**
     * 形象图片上传
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:figure:upload')")
    @Log(title = "形象图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/figure/upload")
    public AjaxResult figureUpload(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!StringUtils.isEmpty(type)) {
                if ("jpg,jpeg,png".contains(type)) {
                    SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_FIGURE, ResConstants.mediaType.IMG, "", file,getLoginUser());
                    return success(sysRes);
                } else if ("avi,wmv,mpeg,mp4,m4v,mov,asf,flv,f4v,rmvb,rm,3gp,vob".contains(type)) {
                    SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_FIGURE, ResConstants.mediaType.VIDEO, "", file,getLoginUser());
                    return success(sysRes);
                } else {
                    SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_FIGURE, ResConstants.mediaType.FILE, "", file,getLoginUser());
                    return success(sysRes);
                }
            }
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

    /**
     * 生长过程图片上传
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:period:upload')")
    @Log(title = "生长过程图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/period/upload")
    public AjaxResult periodUpload(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_PERIOD, ResConstants.mediaType.IMG, "", file,getLoginUser());
            return success(sysRes);
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

    /**
     * 生长环境图片上传
     */
    @PreAuthorize("@ss.hasPermi('tss:sourceinfo:environment:upload')")
    @Log(title = "生长环境图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/environment/upload")
    public AjaxResult environmentUpload(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SOURCE_INFO_ENVIRONMENT, ResConstants.mediaType.IMG, "", file,getLoginUser());
            return success(sysRes);
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

    public String getResUrl (List<SysRes> list) {
        if (list != null && list.size() > 0) {
            String url = "";
            for (SysRes sysRes : list) {
                url += sysRes.getResUrl() + ",";
            }
            url = url.substring(0, url.length() - 1);
            return url;
        } else {
            return "";
        }
    }
    public String getResIds (List<SysRes> list) {
        if (list != null && list.size() > 0) {
            String url = "";
            for (SysRes sysRes : list) {
                url += sysRes.getResId() + ",";
            }
            url = url.substring(0, url.length() - 1);
            return url;
        } else {
            return "";
        }
    }
}
