<template>
    <div>
        <a-button type="primary" @click.stop="show = true">关联项目</a-button>
        <a-modal
            v-model:visible="show"
            width="780px"
            @close="reset"
            @before-ok="update"
        >
            <a-table :columns="columns" :data="list" @row-click="checked">
                <template #name="{ record }">
                    <div class="flex flex-center flex-justify-between">
                        <div>
                            {{ record.name }}
                        </div>
                        <div>
                            <icon-check-circle-fill v-if="record.checked" />
                            <icon-check-circle v-else class="green" />
                        </div>
                    </div>
                </template>
            </a-table>
        </a-modal>
    </div>
</template>

<script>
export default {
    props: {
        contractId: {
            type: String,
            default: ''
        }
    },
    watch: {
        show: {
            handler(val) {
                this.fetchList()
            }
        }
    },
    data() {
        return {
            show: false,
            columns: [
                {
                    title: '项目名称',
                    slotName: 'name'
                }
            ],
            list: [],
            page: { page: 0, size: 10 }
        }
    },
    methods: {
        reset() {
            this.list = this.list.map(e => {
                e.checked = false
                return e
            })
        },
        checked(res) {
            const index = this.list.findIndex(item => item.id === res.id)
            this.list[index].checked = !this.list[index].checked
        },
        fetchList() {
            this.$api.project.page(this.page).then(res => {
                if (res.code === 200) {
                    this.list = res.data.records.map(e => {
                        e.checked = false
                        return e
                    })
                }
            })
        },
        update(done) {
            const data = {
                id: this.contractId,
                projectIds: this.list.map(e => e.id).join(',')
            }
            this.$api.contract.submit(data).then(res => {
                if (res.code === 200) {
                    this.$notification.success(res.msg)
                    this.$emit('ok', res.data.projects)
                    done()
                } else {
                    this.$notification.error(res.msg)
                    done(false)
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped></style>
