public with sharing class ConsumReassignController {
    public string staticResource { get; private set; }
    // 明细行项目
    public List<LineInfo> lineInfoList { get; set; }
    //备品申请书ID
    public String rentalApplyId { get; private set; }
    private String caId;
    public Boolean hasError { get; private set; }
    public Boolean saveBtn { get; private set; }
    public Boolean checkAll { get; set; }
    //现有备品数量（基于备品一览数量）
    public Integer EquipmentSetCnt{get;set;}
    public ConsumReassignController() {
        //Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
        caId = ApexPages.currentPage().getParameters().get('caid');
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Consum_Apply_Equipment_Set_Detail__c'));
    }

    // 画面初始化
    public PageReference init() {
        saveBtn = false;
        hasError = false;
        lineInfoList = new List<LineInfo>();
        List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        if (caId != null && caId.length() > 0) {
            // 耗材借出申请
            caesdList = [
                SELECT Id
                     , AWS_Data_Id__c
                     , Fixture_Model_No_F__c
                     , Asset__c
                     , Consum_Start_Date__c
                     , SerialNumber_F__c
                     , RAESD_Status__c
                     , Trial_Num__c
                     , IndexFromUniqueKey__c
                     , IndexFromUniqueKey_Text__c
                     , Fixture_Model_No_text__c
                     , FSD_Name_CHN__c
                     , Trial_User__c // 试用者
                     , Show_demonstration__c // 展示/演示
                     , Operation_Type__c // 术式类别
                     , Consum_Apply__c
                     , Case_OR_animal_organ__c // 病例/动物脏器
                     , Follower_User__c // 跟台者
                     , Spare__c // 备用
                     , Comment__c // 备注
                     , Degree_Of_Importance__c // 重要性程度
                     , Consum_Apply_Equipment_Set__c
                     , Consum_Apply_Equipment_Set__r.Model_No__c
                     , Consum_Apply_Equipment_Set__r.NG_Select_Again__c
                     , Consum_Apply_Equipment_Set__r.Consum_Apply__c
                     , Consum_Apply_Equipment_Set__r.Consum_Start_Date__c
                     , Consum_Apply_Equipment_Set__r.Old_Consum_Apply__c
                     // , Consum_Apply_Equipment_Set__r.Rental_Num__c
                  FROM Consum_Apply_Equipment_Set_Detail__c
                 WHERE Consum_Apply__c = :caId
                   AND Received_Confirm__c = 'NG'
                   AND Asset_Center_Confirm__c = 'OK'
                   AND Cancel_Select__c = false];
                   // craes.Cancel_Select__c = true;
            // craes.NG_Select_Again__C = true;

            if (caesdList.size() > 0) {
                rentalApplyId = caesdList[0].Consum_Apply_Equipment_Set__r.Consum_Apply__c;
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有可以重新分配的一览明细'));
                saveBtn = true;
                return null;
            }
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '耗材一览不存在，请确认。'));
            saveBtn = true;
            return null;
        }


        // 明细行做成
        for (Consum_Apply_Equipment_Set_Detail__c caesd : caesdList) {
            LineInfo lineInfo = new LineInfo(caesd);
            lineInfoList.add(lineInfo);
        }

        return null;
    }

    // 保存按钮
    // https://sohobb.backlog.jp/view/OLY_OCM-152#comment-20041467
    // TODO OLY_OCM-206 select from 一対一Link, 把 分配数 清 0
    public PageReference saveBtn() {
        List<Consum_Apply_Equipment_Set_Detail__c> delList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        List<Consum_Apply_Equipment_Set_Detail__c> updList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        Set<Id> esIdSet = new Set<Id>();

        // 明细行check
        Integer cntSelect = 0;
        hasError = false;
        Map<String, List<Consum_Apply_Equipment_Set_Detail__c>> caesdMap = new Map<String, List<Consum_Apply_Equipment_Set_Detail__c>>();
        Map<String, Consum_Apply_Equipment_Set__c> caesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
        Map<String, Consum_Apply_Equipment_Set__c> updateCaesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
        Set<String> caesIdSet = new Set<String>();
        for (LineInfo line : lineInfoList) {
            if (line.isSelect == true) {
                Consum_Apply_Equipment_Set_Detail__c upd = new Consum_Apply_Equipment_Set_Detail__c();
                upd = line.caesd;
                upd.Cancel_Select__c = true;
                upd.NG_Select_Again__C = true;
                // upd.Cancel_Date__c = Date.today();
                // upd.Cancel_Time__c = MainFixtureSelectController.getCurrentTime();
                updList.add(upd);

                String model = line.caesd.Consum_Apply_Equipment_Set__r.Model_No__c;

                Consum_Apply_Equipment_Set_Detail__c caesd = new Consum_Apply_Equipment_Set_Detail__c();
                caesd.Consum_Apply__c = line.caesd.Consum_Apply__c;
                // caesd.Consum_Apply_Equipment_Set__c = line.caesd.Consum_Apply_Equipment_Set__c;
                caesd.Canceled__c = upd.Id;
                caesd.IndexFromUniqueKey__c = line.caesd.IndexFromUniqueKey__c;
                caesd.IndexFromUniqueKey_Text__c = line.caesd.IndexFromUniqueKey_Text__c;
                caesd.Fixture_Model_No_text__c = line.caesd.Fixture_Model_No_text__c;
                caesd.FSD_Name_CHN__c    = line.caesd.FSD_Name_CHN__c;
                caesd.Consum_Start_Date__c = line.caesd.Consum_Start_Date__c;
                caesd.Trial_User__c = line.caesd.Trial_User__c; // 试用者
                caesd.Show_demonstration__c = line.caesd.Show_demonstration__c; // 展示/演示
                caesd.Operation_Type__c = line.caesd.Operation_Type__c; // 术式类别
                caesd.Case_OR_animal_organ__c = line.caesd.Case_OR_animal_organ__c; // 病例/动物脏器
                caesd.Follower_User__c = line.caesd.Follower_User__c; // 跟台者
                caesd.Spare__c = line.caesd.Spare__c; // 备用
                caesd.Comment__c = line.caesd.Comment__c; // 备注
                caesd.Degree_Of_Importance__c = line.caesd.Degree_Of_Importance__c; // 重要性程度
                
                caesIdSet.add(line.caesd.Consum_Apply_Equipment_Set__c);

                if (caesdMap.containsKey(model) == false) {
                    caesdMap.put(model, new List<Consum_Apply_Equipment_Set_Detail__c>());
                }
                caesdMap.get(model).add(caesd);
                cntSelect += 1;
                if (upd.Consum_Apply_Equipment_Set__r.NG_Select_Again__c == false) {
                    updateCaesMap.put(upd.Consum_Apply_Equipment_Set__c, new Consum_Apply_Equipment_Set__c(Id = upd.Consum_Apply_Equipment_Set__c, NG_Select_Again__c = true));
                }

                Consum_Apply_Equipment_Set__c caes = new Consum_Apply_Equipment_Set__c();
                // caes.Rental_Num__c = line.caesd.Consum_Apply_Equipment_Set__r.Rental_Num__c;
                caes.Old_Consum_Apply__c = line.caesd.Consum_Apply_Equipment_Set__r.Old_Consum_Apply__c;
                caes.Model_No__c = model;
                caes.Consum_Apply__c = line.caesd.Consum_Apply__c;
                caes.Canceled__c = line.caesd.Consum_Apply_Equipment_Set__c;
                caes.Consum_Start_Date__c = line.caesd.Consum_Apply_Equipment_Set__r.Consum_Start_Date__c;
                caesMap.put(caes.Model_No__c, caes);
            }
        }
        if (cntSelect == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '未选择取消分配的明细。'));
            hasError = true;
        }
        if (hasError == true) {
            system.debug('=====hasError');
            return null;
        }


        // 保存
        Savepoint sp = Database.setSavepoint();
        try {
            System.debug(updateCaesMap);
            if (updateCaesMap.isEmpty() == false) {
                FixtureUtil.withoutUpdate(updateCaesMap.values());
            }
            if (updList.size() > 0) {
                FixtureUtil.withoutUpdate(updList);
                List<Consum_Apply_Equipment_Set__c> caesList = [SELECT Id
                            , Model_No__c
                         FROM Consum_Apply_Equipment_Set__c
                        WHERE Cancel_Select__c = false
                          AND Yi_Assigned_Cnt__c = 0
                          AND Model_No__c = :caesMap.keySet()
                          AND Consum_Apply__c = :rentalApplyId];
                System.debug(caesList);
                for (Consum_Apply_Equipment_Set__c caes : caesList) {
                    caesMap.get(caes.Model_No__c).Id = caes.Id;
                }
                System.debug(caesMap);
                FixtureUtil.withoutUpsertObjects(caesMap.values());
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                for (String model : caesdMap.keySet()) {
                    for (Consum_Apply_Equipment_Set_Detail__c caesd : caesdMap.get(model)) {
                        caesd.Consum_Apply_Equipment_Set__c = caesMap.get(model).Id;
                        caesdList.add(caesd);
                    }
                }
                FixtureUtil.withoutInsert(caesdList);
            }
        }
        catch (Exception ex)    {
            system.debug('=====' + ex.getStackTraceString());
            hasError = true;
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            return null;
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '重新分配成功'));
        return null;
    }

    @TestVisible
    class LineInfo {
        // 选择
        public boolean isSelect { get; set; }
        // 借出备品set一览
        public Consum_Apply_Equipment_Set_Detail__c caesd { get; set; }
        // 状态：可以删除、可以取消、不能取消
        //public String status { get; private set; }
        public String esName { get; private set; }
        public String loanerCode { get; private set; }
        public LineInfo(Consum_Apply_Equipment_Set_Detail__c r) {
            isSelect = false;
            caesd = r;
        }
    }

    @TestVisible private static void test() {
        if (false == Test.isRunningTest()) return;
        Integer i = 0;
        
    }

}