package com.fuint.module.backendApi.controller;

import com.alipay.api.internal.util.StringUtils;
import com.fuint.common.dto.AccountInfo;
import com.fuint.common.dto.MaterialDto;
import com.fuint.common.dto.MaterialSearchDto;
import com.fuint.common.util.AuthUserUtil;
import com.fuint.common.util.TokenUtil;
import com.fuint.common.vo.MaterialVo;
import com.fuint.framework.FrameworkConstants;
import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.PageResult;
import com.fuint.framework.web.ResponseObject;
import com.fuint.common.service.MaterialService;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.model.MtMaterial;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 材料表管理类controller
 *
 * Created by PZG
 * CopyRight https://www.fuint.cn
 */
@Api(tags="管理端-材料表相关接口")
@RestController
@AllArgsConstructor
@RequestMapping(value = "/backendApi/material")
public class BackendMaterialController extends BaseController {

    /**
     * 材料表服务接口
     */
    private MaterialService materialService;



    /**
     * 材料表列表查询
     *
     * @param  request HttpServletRequest对象
     * @return 材料表列表
     */
    @ApiOperation(value = "材料表列表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('material:list')")
    public  ResponseObject list(HttpServletRequest request, MaterialSearchDto materialSearchDto) throws BusinessCheckException {

        AccountInfo accountInfo = AuthUserUtil.get();
        if (accountInfo == null) {
            throw new BusinessCheckException("请先登录");
        }
        String storeId = materialSearchDto.getStoreId();
        if (StringUtils.isEmpty(storeId)){
            storeId = String.valueOf(accountInfo.getStoreId());
            materialSearchDto.setStoreId(storeId);
        }

        PageResult<MaterialVo> result = materialService.selectMaterialList(materialSearchDto);
        return new ResponseObject(FrameworkConstants.HTTP_RESPONSE_CODE_SUCCESS, "操作成功",result);
    }

    /**
     * 更新材料表状态
     *
     * @return 结果
     */
    @ApiOperation(value = "更新材料表状态")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('material:edit')")
    public ResponseObject updateStatus(@RequestBody MaterialDto materialDto) throws BusinessCheckException {

        AccountInfo accountInfo = AuthUserUtil.get();
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        MtMaterial mtMaterial = new MtMaterial();
        BeanUtils.copyProperties(materialDto,mtMaterial);
        MtMaterial rawMaterial = materialService.queryMaterialById(mtMaterial.getId());
        if (rawMaterial == null) {
            return getFailureResult(201,"数据不存在");
        }
        mtMaterial.setUpdateTime(new Date());
        mtMaterial.setUpdateUserId(String.valueOf(accountInfo.getId()));
        materialService.updateMaterial(mtMaterial);

        return getSuccessResult(true);
    }

    /**
     * 保存材料表
     *
     * @return 结果
     */
    @ApiOperation(value = "保存材料表")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('material:list:add')")
    public ResponseObject saveHandler(@RequestBody MaterialDto materialDto) throws BusinessCheckException {

        AccountInfo accountInfo = AuthUserUtil.get();
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
        Long storeId;
        if(StringUtils.isEmpty(materialDto.getStoreId())){
            storeId = AuthUserUtil.get().getStoreId();
        }else{
            storeId = Long.valueOf(materialDto.getStoreId());
        }

        MtMaterial mtMaterial = new MtMaterial();
        BeanUtils.copyProperties(materialDto,mtMaterial);
        if (!Objects.isNull(mtMaterial.getId())) {
            mtMaterial.setUpdateTime(new Date());
            materialService.updateMaterial(mtMaterial);
        } else {
            mtMaterial.setStoreId(Long.valueOf(storeId));
            mtMaterial.setCreateUserId(String.valueOf(accountInfo.getId()));
            mtMaterial.setUpdateUserId(String.valueOf(accountInfo.getId()));
            materialService.addMaterial(mtMaterial);
        }
        return getSuccessResult(true);
    }

    /**
     * 获取材料表详情
     *
     * @param id 材料表id
     * @return 结果
     */
    @ApiOperation(value = "获取材料表详情")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('material:list')")
    public ResponseObject info(HttpServletRequest request, @PathVariable("id") String id) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }

        MtMaterial materialInfo = materialService.queryMaterialById(Long.valueOf(id));

        Map<String, Object> result = new HashMap<>();
        result.put("materialInfo", materialInfo);

        return getSuccessResult(result);
    }

    @ApiOperation(value = "删除材料数据")
    @DeleteMapping(value = "/delete/{id}")
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('material:list:delete')")
    public ResponseObject deleteById(@PathVariable("id") String id) throws BusinessCheckException {
        AccountInfo accountInfo = AuthUserUtil.get();
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }
         materialService.deleteMaterial(Long.valueOf(id), String.valueOf(accountInfo.getId()));
        return getSuccessResult("删除成功");
    }

}
