 <template>
    <h-view id="batch-sign" class="public-style" :title="title">
        <h-header class="bar-custom">
            <div slot="left" class="h-header-btn">
                <img src="@/assets/userBind/arrow.png" @click="goBack()" />
            </div>
            <div slot="center" class="top-word">{{ title }}</div>
        </h-header>

        <scroll ref="scrollLists" :updateData="[prolists]" :pullUp="false">
            <div class="hint-info">
                <img src="@/assets/contractCreate/hint.png" />提示： 仅签署列表中状态为“未签署”的合同
            </div>
            <div class="scroll-box">
                <div class="box" v-for="item of list" :key="item.project_id">
                    <!-- 颜色 d6204b -->
                    <div class="name">
                        <!-- <img src="@/assets/login/contract.png" alt="icon" /> -->
                        <img src="@/assets/distributorSign/fileIcon.png" alt="icon" />
                        <!-- <img v-if="item.checked" src="@/assets/login/contract-red.png" alt="icon" /> -->
                        <span>{{ item.project_number }}</span>
                    </div>
                    <div
                        :class="['flag', item.checked ? 'flag-false' : null]"
                    >{{ item.checked ? '已' : '未' }}签署</div>
                </div>
            </div>
        </scroll>

        <bottom-tab class="add-box">
            <tab-button
                class="before"
                @click.native="$route.query.name === 'confirmList' ? takePhonto() : signContact()"
            >{{ buttonName }}</tab-button>
            <tab-button class="next" @click.native="confirm">提交审核</tab-button>
        </bottom-tab>
    </h-view>
</template>

<script>
export default {
    name: 'batch-sign',
    data() {
        return {
            prolists: [],
            title: this.$route.query.name === 'confirmList' ? '批量签署电子合同' : '批量签署征信授权书',
            buttonName: this.$route.query.name === 'confirmList' ? '签署电子合同' : '签署征信授权',
            list: JSON.parse(window.localStorage.getItem('handleContact')),
            checkList: [], // 需要进行签署的合同

            faceListUpload: [],
        }
    },
    created() {
        this.checkSigned();
    },
    methods: {
        // 检测已经签署的合同，进行过滤
        async checkSigned() {
            if (!this.list.length) return;

            let url = process.env.basePath + 'batch_check_sign';

            let data_class = this.$route.query.name === "confirmList" ? "LEASE_ITEM" : "PRJ_CONFIRM";
            let param = { "master": this.list.map(item => ({ confirm_id: item.confirm_id, data_class })) };

            hlsPopup.showLoading('请稍候');
            let res = await this.$post(url, param);
            this.hlsPopup.hideLoading();

            if (res.result === "S") {
                let checkList = res.lists.filter(ele => ele.signed_flag === 'N').map(ele => ele.confirm_id);

                this.checkList = this.list.filter(ele => checkList.includes(ele.confirm_id));

                // 加标识， checked为true 为 已签署
                this.list = this.list.map(ele => {
                    ele.checked = !checkList.includes(ele.confirm_id);
                    return ele;
                })
            } else {
                hlsPopup.showLongCenter(res.message);
            }
        },

        confirm() {
            let vm = this;
            hlsPopup.showConfirm({
                title: '提交审核',
                content: '仅提交已签署成功合同，请确认是否提交？',
                onConfirm: function (index) {
                    if (index == 1) vm.submit();
                },
            })
        },
        // 提交
        async submit() {
            let data_class = this.$route.query.name === "confirmList" ? "LEASE_ITEM" : "PRJ_CONFIRM";
            let confirm_list = this.list.filter(item => item.checked).map(item => ({ confirm_id: item.confirm_id, data_class, confirm_status: "APPROVED" }));
            if (!confirm_list.length) return hlsPopup.showLongCenter("无可提交审核的合同");

            let url = process.env.basePath + 'batch_do_confirm_bp';
            let param = { master: { confirm_list } };

            hlsPopup.showLoading('提交数据中');
            let res = await this.$post(url, param);
            this.hlsPopup.hideLoading();

            if (res.result === 'S') {
                this.hlsPopup.showSuccess('提交成功');

                let successList = res.info.filter(item => item.status == 'S').map(item => item.confirm_id);

                this.list = this.list.filter(item => !successList.includes(item.confirm_id));

                if (!this.list.length) this.goBack();

                window.localStorage.setItem('handleContact', JSON.stringify(this.list));

                await this.checkSigned();
            } else {
                this.hlsPopup.showLongCenter(res.message);
            }
        },
        // 签署
        async signContact() {
            if (!this.checkList.length) return hlsPopup.showLongCenter("无可需要签署的电子合同");

            let url = process.env.basePath + 'batch_sign';
            let data_class = this.$route.query.name === "confirmList" ? "LEASE_ITEM" : "PRJ_CONFIRM";
            let param = {
                master: {
                    project_list: this.checkList.map(item => ({ project_id: item.project_id, data_class })),
                    bp_id: JSON.parse(window.localStorage.getItem('now_user_bp_bind_id')).bp_id
                }
            }

            hlsPopup.showLoading('请稍候');
            let res = await this.$post(url, param);
            this.hlsPopup.hideLoading()

            if (res.result == 'S' && res.info.msg === 'success') {
                this.$router.push({
                    name: 'ElectronicSign',
                    params: { url: res.info.data.url },
                })
            } else {
                hlsPopup.showLongCenter(res.message || res.info.msg)
            }
        },

        // 人脸识别验证 
        async takePhonto() {
            if (!this.checkList.length) return hlsPopup.showLongCenter("无可需要签署的电子合同");

            let vm = this

            let url = process.env.basePath + 'bp_query'
            let param = { bp_id: JSON.parse(window.localStorage.now_user_bp_bind_id).bp_id }
            hlsPopup.showLoading('请稍候')

            vm.hlsHttp.post(url, param).then(res => {
                hlsPopup.hideLoading()
                if (res.result === 'S') {
                    let data = res.lists[0]
                    cordova.plugins.IdCardPlugin.faceContrast({ 'idNum': data.id_card_no, 'idName': data.bp_name }, function (suc) {
                        let success = JSON.parse(suc)
                        if (success.code === 1) {
                            let filePath = JSON.stringify(success.message, '\\', null)
                            filePath = 'file:\/\/' + filePath.replace('\"', '')
                            filePath = filePath.substr(0, filePath.length - 1)
                            console.log('filePath ==== ' + filePath)
                            // 回调成功上传图片
                            vm.uploadImg(filePath)
                            vm.signContact()
                        }
                    }, function (reason) {
                        let error = JSON.parse(reason)
                        vm.hlsPopup.showLongCenter('认证失败: ' + error.message)
                    })
                } else {
                    vm.hlsPopup.showLongCenter(res.message)
                }
            })
        },
        // 处理要上传的图片格式
        uploadImg(img) {
            this.faceListUpload = this.list.map(item => {
                return {
                    pkvalue: item.check_id,
                    source_type: 'PRJ_CDD_ITEM_CHECK',
                    picture: '',
                    filePath: img,
                    attachment_id: '',
                    user_id: 1,
                    fileName: 'face',
                }
            })
            this.save_picture(this.faceListUpload);
        },
        // 图片保存
        save_picture(list) {
            let vm = this
            if (list.length) {
                // hlsPopup.showLoading('图片上传请稍候')
                var alreadyUploadNum = 0
                var attLength = 0
                var recordUploadInterval = setInterval(function () {
                    if (alreadyUploadNum === attLength) {
                        clearInterval(recordUploadInterval)
                    }
                }, 500)
                for (var i = 0; i < list.length; i++) {
                    let uploadSuccess = function (res) {
                        if (res.result === 'S') {
                            alreadyUploadNum++
                            for (var j = 0; j < list.length; j++) {
                                if (list[j].filePath === res.response.filePath) {
                                    list[j].attachment_id = res.response.attachment_id
                                    vm.faceListUpload.push(list[j])
                                    break
                                }
                            }
                        } else {
                            hlsPopup.hideLoading()
                        }
                    }
                    if (!list[i].attachment_id) {
                        attLength++
                        hlsUtil.fileUploadSvc(list[i], uploadSuccess)
                    }
                }
            } else {
                hlsPopup.hideLoading()
            }
        },

        // 返回，清缓存
        goBack() {
            window.localStorage.removeItem("handleContact");
            this.$router.go(-1);
        }
    },
}
</script>

<style lang='less'>
#batch-sign {
    background-color: rgb(242, 242, 242);
    .scrollContent {
        background-color: rgb(242, 242, 242);
    }
    .hint-info {
        width: 100%;
        height: 36px;
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #fcc800;
        letter-spacing: 0.5px;
        background-color: #faf5e0;
        display: flex;
        align-items: center;

        img {
            width: 16px;
            height: 16px;
            margin-left: 17px;
            margin-right: 12px;
        }
    }
    .add-box {
        .before {
            border: 1px solid #fdb62f;
            border-radius: 4px;
            color: #fdb62f;
        }
        .next {
            background: #1d3fff;
            border-radius: 4px;
            color: #fff;
        }
    }

    .scroll-box {
        padding: 8px;

        .box {
            display: flex;
            justify-content: space-between;
            align-items: center;

            width: 99.9%;
            height: 60px;
            padding: 0 15px 0 10px;
            background-color: #fff;
            border-radius: 8px;
            line-height: 60px;
            font-size: 80%;
            color: rgb(58, 58, 58);
            margin-bottom: 0.15rem;

            img {
                height: 22px;
                vertical-align: middle;
                margin-right: 7px;
            }

            .flag {
                height: 25px;
                line-height: 25px;
                padding: 0 2px;
                border-radius: 5px;
                font-weight: 500;

                background-color: #fff;
                color: #bebebf;
                border: 2px solid #bebebf;
            }

            .flag-false {
                background-color: #00469c;
                color: #e9e9eb;
                border: 2px solid #00469c;
            }
        }
    }

    .content {
        position: absolute;
        top: 0;
    }

    .scrollContent {
        //padding-top: 1.92rem;
        padding-bottom: 20px;
    }
}

.platform-ios {
    #batch-sign {
        .scrollContent {
            padding-top: 2.32rem;
            padding-bottom: 50px;
        }
    }
}

// iPhoneX适配
@media (device-width: 375px) and (device-height: 812px) and (-webkit-min-device-pixel-ratio: 3) {
    .platform-ios {
        #query {
            .scrollContent {
                padding-top: 2.72rem;
            }
        }
    }
}

// iPhoneXR适配
@media (device-width: 414px) and (device-height: 896px) {
    .platform-ios {
        #query {
            .scrollContent {
                padding-top: 2.72rem;
            }
        }
    }
}
</style>
