package com.bzd.web.controller.dtp;

import com.bzd.common.annotation.Log;
import com.bzd.common.config.HealthConfig;
import com.bzd.common.config.dao.PageData;
import com.bzd.common.core.controller.BaseController;
import com.bzd.common.core.domain.AjaxResult;
import com.bzd.common.core.page.TableDataInfo;
import com.bzd.common.enums.BusinessType;
import com.bzd.common.utils.StringUtils;
import com.bzd.common.utils.file.FileUploadUtils;
import com.bzd.common.utils.file.MimeTypeUtils;
import com.bzd.common.utils.poi.ExcelUtil;
import com.bzd.system.service.DTPService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

import static com.bzd.common.config.datasource.DynamicDataSourceContextHolder.log;

/**
 * 处方登记管理
 * creator wsp
 */
@Controller
@RequestMapping("/dtp/recipe")
public class RecipeRegisterController extends BaseController {

    private String prefix = "dtp/recipe";
    private String prefix_archives = "dtp/archives";

    @Autowired
    private DTPService dtpService;
    @RequiresPermissions("dtp:recipe:view")
    @GetMapping()
    public String recipe()
    {
        return prefix + "/recipe";
    }

/**
 *
 * 处方登记查询
 */
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list() throws Exception {
        PageData pd = this.getPageData();

        startPage();
        pd.put("sales_is", 4);//4: "待处方登记";\r\n5: "待订单销售"
        List<PageData> pageData = dtpService.findForList(pd);
        return  getDataTable(pageData);
    }
    /**
     *
     * 先销售后登记的处方订单查询
     */
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/salesList")
    @ResponseBody
    public TableDataInfo salesList() throws Exception {
        PageData pd = this.getPageData();
        startPage();
        pd.put("status", 4);
        pd.put("sales_yes", 4);//4: "待处方登记";\r\n5: "待订单销售"
        List<PageData> pageData = dtpService.findForList(pd);
        return  getDataTable(pageData);
    }
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/getLastRecipe")
    @ResponseBody
    public AjaxResult getLastRecipe( ModelMap mmap) throws Exception {
        PageData pd = this.getPageData();
        startPage();
        PageData pageData =dtpService.getLastRecipe(pd);
//        List<PageData> recipeList = (List<PageData>) pageDataList.get("recipeList");
//        Object recipe = pageData.get("recipe");
//        mmap.put("recipe", recipe);
//        mmap.put("recipeList", recipeList);
        return  AjaxResult.success(pageData);
    }

    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/getLastRecipeInfo")
    @ResponseBody
    public AjaxResult getLastRecipeInfo( ModelMap mmap) throws Exception {
        PageData pd = this.getPageData();
        startPage();
        PageData pageData =dtpService.getLastRecipeInfo(pd);
        return  AjaxResult.success(pageData);
    }
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/getLastRecipeInfoSales")
    @ResponseBody
    public AjaxResult getLastRecipeInfoSales( ModelMap mmap) throws Exception {
        PageData pd = this.getPageData();
        startPage();
        PageData pageData =dtpService.getLastRecipeInfoSales(pd);
        return  AjaxResult.success(pageData);
    }

    /**
     * 新增页面
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("posts", 1);
        return prefix + "/add";
    }
    /**
     * 新建登记
     */
    @GetMapping("/newRecipe")
    public String newRecipe(ModelMap mmap)
    {
        mmap.put("posts", 1);
        return prefix + "/newRecipe";
    }
    /**
     * 药品信息页面
     */
    @RequiresPermissions("dtp:recipe:view")
    @GetMapping("/drugInfo")
    public String drugInfo(ModelMap mmap)
    {
        mmap.put("posts", 1);
        return prefix + "/drugInfo";
    }
    /**
     * 绑定患者页面弹框
     */
    @RequiresPermissions("dtp:recipe:view")
    @GetMapping("/huanzheBanding")
    public String huanzheBanding(ModelMap mmap)
    {
        mmap.put("posts", 1);
        return prefix + "/huanzheBanding";
    }


    /**
     *
     * 先销售后登记的处方订单添
     */
    @GetMapping("/saveSalesPage")
    public String saveSalesPage(ModelMap mmap)
    {
        mmap.put("posts", 1);
        return prefix + "/saveSalesPage";
    }
    /**
     * 先销售后登记的处方订单添
     */
    @RequiresPermissions("dtp:recipe:add")
    @Log(title = "先销售后登记的处方订单添", businessType = BusinessType.INSERT)
    @PostMapping("/saveSales")
    @ResponseBody
    public AjaxResult saveSales() throws Exception {
        PageData pd = new PageData();
        pd = this.getPageData();
        PageData object = dtpService.saveSales(pd);
        return AjaxResult.success(object.get("result").toString(),object);
    }


    /**
     * 处方登记新增保存-----暂时废弃改代码
     */
    //@RequiresPermissions("server:serv:add")
    @Log(title = "处方登记新增", businessType = BusinessType.INSERT)
    @PostMapping("/SaveRecipe")
    @ResponseBody
    public AjaxResult SaveRecipe() throws Exception {
        PageData pd = new PageData();
        pd = this.getPageData();
        PageData object = dtpService.save(pd);
        return AjaxResult.success(object.get("result").toString(),object);
    }
    /**
     * 处方登记保存
     */
    //@RequiresPermissions("server:serv:add")
    @Log(title = "处方登记", businessType = BusinessType.INSERT)
    @PostMapping("/saveCFDJ")
    @ResponseBody
    public AjaxResult saveCFDJ() throws Exception {
        PageData pd = this.getPageData();
        PageData p = dtpService.saveCFDJ(pd);
        if(p.get("code").toString().equals("200")){
            return AjaxResult.success(p);
        }else{
            return AjaxResult.error(p.get("msg").toString(),"");
        }

    }

    @Log(title = "处方修改", businessType = BusinessType.INSERT)
    @PostMapping("/updateCFDJ")
    @ResponseBody
    public AjaxResult updateCFDJ() throws Exception {
        PageData pd = new PageData();

        pd = this.getPageData();
        try{
            int i = dtpService.updateCFDJ(pd);
            if(i>0){
                return AjaxResult.success("修改成功");
            }else {
                return AjaxResult.error("修改失败");
            }
        }catch (Exception e){
            return AjaxResult.error("修改失败"+e);
        }


    }

    /**
     * 保存处方照片
     */
    @Log(title = "处方信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePrescriptionImg")
    @ResponseBody
    public AjaxResult updatePrescriptionImg(@RequestParam("prescriptionfile") MultipartFile file)
    {
        try
        {
            if (!file.isEmpty())
            {
                String prescriptionImg = FileUploadUtils.upload(HealthConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                    return success(prescriptionImg);
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改处方信息失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 图片上传 通用
     */
    @Log(title = "图片上传", businessType = BusinessType.OTHER)
    @PostMapping("/uploadImg")
    @ResponseBody
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile file)
    {
        try
        {
            if (!file.isEmpty())
            {
                String prescriptionImg = FileUploadUtils.upload(HealthConfig.getUploadPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                return success(prescriptionImg);
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("上传图片失败！", e);
            return error(e.getMessage());
        }
    }


    @Log(title = "处方登记删除", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove() throws Exception
    {
        PageData pd = new PageData();
        pd = this.getPageData();
       Object id = pd.get("ids");
       if(StringUtils.isNotNull(id)){
           String[] split = id.toString().split(",");
           List<String> ids = Arrays.asList(split);
           Integer integer = dtpService.del(ids);
           return toAjax(integer);

       }
        return AjaxResult.success("请选择要删除的数据");
    }

    @RequiresPermissions("dtp:recipe:edit")
    @GetMapping("/edit/{id}")
    public String view(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);
        pd.put("sales_is", "0");
        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/edit";
    }
    /**
     * 绑定患者
     */
    @RequiresPermissions("dtp:recipe:edit")
    @Log(title = "档案管理修改", businessType = BusinessType.UPDATE)
    @PostMapping("/BandingRecipe")
    @ResponseBody
    public AjaxResult BandingRecipe() throws Exception {
        PageData pd = this.getPageData();
        try {
            Integer integer = dtpService.BandingRecipe(pd);
            if (integer == 1) {
                return AjaxResult.success("绑定成功");
            } else {
                return AjaxResult.error("绑定失败");
            }
        } catch (Exception e) {
            // 异常处理
            logger.error("Error occurred while updating archives with ID: {}, Exception: {}", pd.get("id"), e.getMessage(), e);
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }
    @RequiresPermissions("dtp:recipe:edit")
    @GetMapping("/BandingPatient/{id}")
    public String Banding(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);
        pd.put("sales_is", "0");
        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/edit";
    }


    /**
     * 保存处方登记修改信息
     */
    @RequiresPermissions("dtp:recipe:edit")
    @Log(title = "处方登记管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave() throws Exception
    {
        PageData pd = this.getPageData();
        Integer update = dtpService.update(pd);
        if(update!=1){
            return error("修改失败");
        }
        return toAjax(dtpService.update(pd));
    }
    /**
     *
     * 校验患者姓名和手机是否存在
     */
    @RequiresPermissions("dtp:recipe:checkPatientNameUnique")
    @PostMapping("/checkPatientNameAndPhoneUnique")
    @ResponseBody
    public boolean checkPatientNameAndPhoneUnique() throws Exception {
        PageData pd = this.getPageData();
        return  dtpService.checkPatientNameAndPhoneUnique(pd);
    }


    @Log(title = "处方信息", businessType = BusinessType.EXPORT)
    @RequiresPermissions("dtp:recipe:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export()throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("sales_is", "0");
        List<PageData> pageData= dtpService.findForList(pd);
        ExcelUtil<PageData> util = new ExcelUtil<>(PageData.class);
        return util.exportExcel(pageData, "处方数据");
    }

    @RequiresPermissions("dtp:recipe:view")
    @GetMapping("/viewInfo/{id}")
    public String viewInfo(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);
        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/newRecipeView";
    }
    @RequiresPermissions("dtp:recipe:view")
    @GetMapping("/viewSalesInfo/{id}")
    public String viewSalesInfo(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);
        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/newRecipeView";
    }
    @RequiresPermissions("dtp:recipe:edit")
    @GetMapping("/viewEditInfo/{id}")
    public String viewEditInfo(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);

        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/edit";
    }
    @RequiresPermissions("dtp:recipe:edit")
    @GetMapping("/viewEditSalesInfo/{id}")
    public String viewEditSalesInfo(@PathVariable("id") String id, ModelMap mmap)throws Exception
    {
        PageData pd = this.getPageData();
        pd.put("id",id);
        PageData pageData = dtpService.findForList(pd).get(0);
        mmap.putAll(pageData);
        return prefix + "/edit";
    }

    /**
     * 验证药师密码
     * @param
     * @return
     * @throws Exception
     */
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/ReviewCheckInputPassword")
    @ResponseBody
    public AjaxResult ReviewCheckInputPassword(ModelMap mmap) throws Exception {

        PageData pd = this.getPageData();
        System.out.println("password:"+pd.get("password"));
        PageData pageData =dtpService.ReviewCheckInputPassword(pd);
        if(StringUtils.isNotNull(pageData)){
            return  AjaxResult.success(pageData);
        }else {
            return  AjaxResult.error("密码错误");
        }

    }
    /**
     * 药师审核处方
     * @param
     * @return
     * @throws Exception
     */
    @RequiresPermissions("dtp:recipe:list")
    @PostMapping("/review")
    @ResponseBody
    public AjaxResult review(ModelMap mmap) throws Exception {

        PageData pd = this.getPageData();
        PageData p =dtpService.Review(pd);
        if(p.get("code").toString().equals("200")){
            return AjaxResult.success(p);
        }else{
            return AjaxResult.error(p.get("msg").toString());
        }

    }

    /**
     * 获取所有药师
     * @param mmap
     * @return
     * @throws Exception
     */
    @PostMapping("/findRevieForList")
    @ResponseBody
    public AjaxResult findRevieForList( ModelMap mmap) throws Exception {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> pageData =dtpService.findRevieForList(pd);
        return  AjaxResult.success(pageData);
    }


    /**
     * 查询s_gxhpz_zd_icd11
     */
    @RequiresPermissions("dtp:recipe:view")
    @PostMapping("/searchICD11")
    @ResponseBody
    public AjaxResult searchICD11() throws Exception {
        PageData pd = this.getPageData();
        List<PageData> pds =dtpService.searchICD11(pd);
        return  AjaxResult.success(pds);
    }
    /**
     * 查询s_gxhpz_zd_icd11 根据id
     */
    @RequiresPermissions("dtp:recipe:view")
    @PostMapping("/searchICD11Object")
    @ResponseBody
    public AjaxResult searchICD11Object() throws Exception {
        PageData pd = this.getPageData();
        String query = (String) pd.get("query");
        if(StringUtils.isNull(query)){
            return AjaxResult.success();
        }
        PageData pdo =dtpService.searchICD11Object(pd);
        return  AjaxResult.success(pdo);
    }




}
