public class SelectAssetExtension {

    private String targetHospitalId { get; set; }

    private String targetContractId { get; set; }

    // 引数のサービス契約の情報を格納する。
    public Maintenance_Contract__c contract { get; set; }

    // 病院配下の納入機器の情報を格納する。
    //public List<Asset> assetRecords { get; set; }//20191220 modify
    //public static  List<Asset> assetRecords  = new List<Asset>();
    public List<List<Asset>> assetLists { get; set; }

    public Integer getProductCount() {
        //return this.assetRecords.size();
        Integer listSize = assetLists.size();

        Integer pCount = 0;
        if (listSize > 0) {
            for (Integer i = 0; i < listSize; i++) {
                List<Asset> aList = assetLists.get(i);
                pCount += aList.size();
            }
        }
        return pCount;
    }

    // 選択済みの納入機器の
    public List<Maintenance_Contract_Asset__c> selectedAsset { get; set; }
    public List<Maintenance_Contract_Asset_Estimate__c> selectedAsset2 { get; set; }
    //public List<Maintenance_Contract_Asset_Estimate__c> selectedAsset2{ get; set; }
    public String sortKey { get; set; }
    public String preSortKey { get; set; }
    public Boolean sortOrderAsc { get; set; }

    public String[] sortOrder { get; set; }

    public String[] columus = new String[] { 'asset.name',
            'asset.SerialNumber',
            'asset.Department_Name__c',
            'asset.Installation_Site__c',
            'asset.Posting_Date__c',
            'asset.Asset_Owner__c'
                                           };

    public void init() {

        List<Asset> assetRecords  = new List<Asset>();//20191220 add
        // サービス契約の情報を取得
        try {
            this.contract = [SELECT Id, Name, Management_Code__c, Hospital__c, Contract_Start_Date__c, Contract_End_Date__c FROM Maintenance_Contract__c WHERE Id = :this.targetContractId][0];
            this.targetHospitalId = this.contract.Hospital__c;
        } catch ( System.ListException le) {
            this.contract = new Maintenance_Contract__c();
        }

        // 納入機器の情報を取得
        if ( this.targetHospitalId == null || ( this.targetHospitalId.length() != 15 && this.targetHospitalId.length() != 18)) {
            //this.assetRecords  = new List<Asset>();
            system.debug('assetRecords123456789==' + assetRecords);
        } else {
            // HWAG-BHD66X start
            assetRecords = [SELECT Id, Name, CheckBox__c, SerialNumber,TransferToOther__c	/*临时用*/,
                            Department_Name__c, Installation_Site__c, Posting_Date__c,
                            Asset_Owner__c,	Product2Id
                            // Gzw 20200826 保存上一期合同临时用 start
                            , Remarks__c,MDM_Model_No__c
                            // Gzw 20200826 保存上一期合同临时用 end
                            // fxk 2021/9/17 点检对象临时用 star
                            // , Freeze_sign__c
                            // fxk 2021/9/17 点检对象临时用 end
                            FROM Asset
                            WHERE Hospital__c = :this.targetHospitalId
                                                // XLIU-CK46FR zyh start
                                                AND Status != '廃棄' AND Status != '待报废' 
                                                AND (Competitor_Name__c = '奥林巴斯' OR Competitor_Name__c = '' OR Competitor_Name__c = '其他')
                                                AND Category1__c != 'ET'
                                                AND (Category1__c != 'SP' OR Category2__c != '附属品' )
                                                AND (Category1__c != 'GI' OR Category2__c != '附属品' OR Category4__c != 'OER' )
                                                AND (Category1__c != 'GI' OR Category2__c != '其他' )
                                                AND (Category1__c != 'ENG' OR Category2__c != '附属品' )
                                                AND (Category1__c != 'ENG' OR Category2__c != '耗材' )
                                                // AND (Category1__c != 'SP' OR Category2__c != '附属品' )
                                                // AND (Category1__c != 'GI' OR (Category2__c != '附属品' OR Category2__c != '其他') )
                                                // AND (Category1__c != 'ENG' OR (Category2__c != '附属品' OR Category2__c != '耗材') )
                                                // AND AssetMark__c != '耗材' 
                                                // XLIU-CK46FR zyh end
                                                AND ( AssetMark__c != '耗材' OR Product2.Family != 'ET' )
                                                ORDER BY Department_Name__c, Posting_Date__c, SerialNumber
                                                ];
            // system.debug('assetRecords123456789' + assetRecords);
            system.debug('assetRecords123456789' + assetRecords.size());
            // HWAG-BHD66X end
        }

        // 選択済みの納入機器情報を取得
        this.selectedAsset = [SELECT Id, Name, Check_object__c, Maintenance_Contract__c, LastMContract__c, Asset__c FROM Maintenance_Contract_Asset__c WHERE Maintenance_Contract__c = :this.targetContractId];
        system.debug('selectedAsset==========>'+selectedAsset);
        //Maintenance_Contract_Asset_Estimate__c
        this.selectedAsset2 = [SELECT Id, Name,Product_Manual__c,Product_Manual__r.MDM_Model_No__c, Check_object__c,Maintenance_Contract_Estimate__r.Maintenance_Contract__c,Asset__c,Asset__r.product2Id 
        FROM Maintenance_Contract_Asset_Estimate__c WHERE Maintenance_Contract_Estimate__r.Maintenance_Contract__c = :this.targetContractId];
        system.debug('selectedAsset2==========>'+selectedAsset2);
        //SELECT Id, Name, Check_object__c, Asset__c FROM Maintenance_Contract_Asset_Estimate__c WHERE 	Maintenance_Contract_Estimate__r.Maintenance_Contract__c = 'a0H1m000002shhL'
        // 選択済みのものにチェックを付ける
        Boolean selected = false;
        for ( Asset local  : assetRecords) {
            selected = false;
            local.Remarks__c = null;
            local.TransferToOther__c = null;
            // local.Freeze_sign__c = false;
            for ( Maintenance_Contract_Asset__c selectedLocal : this.selectedAsset) {
                if ( local.Id == selectedLocal.Asset__c) {
                    local.CheckBox__c = true;
                    local.Remarks__c = selectedLocal.LastMContract__c;
                    local.TransferToOther__c = selectedLocal.Check_object__c;
                    //占用一个复选框字段用于展示“点检对象”
                    // fxk 2021/9/17 点检对象临时用 star
                    // local.Freeze_sign__c = selectedLocal.Check_object__c;
                    // fxk 2021/9/17 点检对象临时用 end
                    selected = true;
                    break;
                }
            }
            for(Maintenance_Contract_Asset_Estimate__c selectedLocal : this.selectedAsset2){
                if(local.MDM_Model_No__c == selectedLocal.Product_Manual__r.MDM_Model_No__c){
                    //local.TransferToOther__c = true;
                    local.TransferToOther__c = selectedLocal.Check_object__c;
                    system.debug('TransferToOther__c============>'+local.TransferToOther__c);
                }
                
            }
            if ( selected == true) {
                continue;
            }
        }
        // List<Asset> assetRecordsv = new List<Asset>(); 
        // for(Asset local : assetRecords){
        //      local.Internal_Asset_photo__c = false;
        //      for(Maintenance_Contract_Asset_Estimate__c equipment : this.selectedAsset2){
        //         if(local.Id == equipment.Maintenance_Contract_Estimate__r.Maintenance_Contract__c){
        //             local.Internal_Asset_photo__c = equipment.Check_object__c;
        //         }
        //     }
        //     assetRecordsv.add(local);
        // }
        this.sortKey = '0';
        this.preSortKey = '0';
        this.sortOrderAsc = true;
        this.sortOrder = new String[6];
        this.sortOrder = new String[] { '↓', '　', '　', '　', '　', '　',' '};
        
        //system.debug('assetRecordsv            '+assetRecordsv);
        this.cutListSize(assetRecords);
    }

    //private void cutListSize() {//20191220 modify
    private void cutListSize(List<Asset> assetRecordsv) {
        this.assetLists = new List<List<Asset>>();
        List<Asset> tempList = new List<Asset>();
        //for (Integer i = 0; i < this.assetRecords.size(); i++) {//20191220 modify
        for (Integer i = 0; i < assetRecordsv.size(); i++) {
            //Asset a = this.assetRecords.get(i);//20191220 modify
            Asset a = assetRecordsv.get(i);
            if (Math.mod(i, 1000) == 0) {
                if ( tempList.size() > 0) {
                    assetLists.add(tempList);
                }
                tempList = new List<Asset>();
            }
            tempList.add(a);
        }
        if (tempList.size() > 0) {
            this.assetLists.add(tempList);
        }

        //this.assetRecords.clear()//20191220 modify
        assetRecordsv.clear();
    }

    //private void mergeList() {//20191220 modify
    private List<Asset> mergeList() {
        List<Asset> assetRecords  = new List<Asset>();//20191220 add
        Integer listSize = this.assetLists.size();
        if (listSize == 1) {
            assetRecords.addAll(this.assetLists.get(0));
        } else {
            for (Integer i = 0; i < listSize; i++) {
                assetRecords.addAll(this.assetLists.get(i));
            }
        }
        return assetRecords;//20191220 add
    }

    /**
     * Visaulforceから呼ばれるコンストラクタです。
     */
    public SelectAssetExtension( ApexPages.StandardController controller) {
        this.targetContractId = (String)(ApexPages.currentPage().getParameters().get( 'targetContractId'));
        this.init();
    }

    /**
     * 保存メソッドです。
     */
    public PageReference save() {
        // Map<String,Boolean> mCAssetEstMap = new Map<String,Boolean>();
        // List<Maintenance_Contract_Asset_Estimate__c> mCAssetEstList = [select Id, Check_Object__c, Maintenance_Contract_Estimate__c, Product_Manual__r.Name 
        //                                                                 from Maintenance_Contract_Asset_Estimate__c 
        //                                                                 where Check_Object__c = true and Maintenance_Contract_Estimate__r.Estimation_Decision__c = true 
        //                                                                 and Maintenance_Contract_Estimate__r.Maintenance_Contract__c =: targetContractId ];
        // for(Maintenance_Contract_Asset_Estimate__c mCAssetEstinfo : mCAssetEstList){
        //     mCAssetEstMap.put(mCAssetEstinfo.Product_Manual__r.Name, mCAssetEstinfo.Check_Object__c);
        // }
        //this.mergeList();//20191220 modify
        List<Asset> assetRecords  = new List<Asset>();//20191220 add
        assetRecords = this.mergeList();
        List<Maintenance_Contract_Asset__c> insertTarget = new List<Maintenance_Contract_Asset__c>();
        Maintenance_Contract_Asset__c target = null;
        for ( Asset input : assetRecords) {
            if ( input.CheckBox__c == true) {
                target = new Maintenance_Contract_Asset__c();
                target.Maintenance_Contract__c = this.targetContractId;
                target.Asset__c = input.Id;
                target.LastMContract__c = input.Remarks__c;
                target.Check_object__c = input.TransferToOther__c;
                // fxk 2021/9/17 点检对象临时用 star
                // target.Check_object__c = input.Freeze_sign__c;
                // fxk 2021/9/17 点检对象临时用 end
                insertTarget.add( target);
            }
        }

        // delete and insertする
        if ( this.selectedAsset.size() > 0) {
            delete selectedAsset;
        }
        if ( insertTarget.size() > 0) {
            insert insertTarget;
        }
        system.debug('insertTarget=============>'+insertTarget);
        return cancel();
    }

    /**
     * キャンセルメソッドです。
     */
    public PageReference cancel() {
        PageReference ret = null;
        if ( this.targetContractId != null) {
            ret = new PageReference( '/' + this.targetContractId);
        }
        return ret;
    }

    /**
     * ソートメソッドです。
     */
    public void sortTable() {

        System.debug( '-----:sortTable start!!');
        //this.mergeList();//20191220 modify
        List<Asset> assetRecords  = new List<Asset>();//20191220 add
        assetRecords = this.mergeList();
        // check済み退避
        List<Asset> checkedAssets = new List<Asset>();
        for ( Asset local : assetRecords) {
            if ( local.checkBox__c == true) {
                checkedAssets.add( local);
            }
        }

        if ( this.sortKey == this.preSortKey) {
            // 方向が変わるのみ
            this.sortOrderAsc = !this.sortOrderAsc;
            this.sortOrder[Integer.valueOf( this.sortKey)] = ( this.sortOrderAsc == true ? '↓' : '↑');
        } else {
            this.sortOrderAsc = true;
            this.sortOrder[Integer.valueOf( this.preSortKey)] = '　';
            this.sortOrder[Integer.valueOf( this.sortKey)] = ( this.sortOrderAsc == true ? '↓' : '↑');
        }
        this.preSortKey = this.sortKey;
        // HWAG-BHD66X start
        string sqlstr = 'SELECT Id, Name, CheckBox__c,' +
                        'SerialNumber, Department_Name__c, ' +
                        ' Installation_Site__c, Posting_Date__c, ' +
                        'Asset_Owner__c FROM Asset WHERE Hospital__c = \'' +
                        this.targetHospitalId +
                        '\' AND ( AssetMark__c != \'耗材\' OR Product2.Family != \'ET\' )' +
                        ' ORDER BY ' + this.columus[Integer.valueOf(this.sortKey)]
                        + ' ' + (this.sortOrderAsc == true ?
                                 'ASC NULLS FIRST' : 'DESC NULLS LAST');
        System.debug(sqlstr);
        assetRecords = Database.query(sqlstr);
        // HWAG-BHD66X end
        // 選択済みのものにチェックを付ける
        Boolean selected = false;
        for ( Asset local  : assetRecords) {
            selected = false;
            local.Remarks__c = null;
            for ( Asset selectedLocal : checkedAssets) {
                if ( local.Id == selectedLocal.Id) {
                    local.CheckBox__c = true;
                    local.Remarks__c = selectedLocal.Remarks__c;

                    selected = true;
                    break;
                }
            }
            if ( selected == true) {
                continue;
            }
        }
        this.cutListSize(assetRecords);

        System.debug( '-----:sortTable end!!');

    }
}