<template>
    <BaseContainer style="padding: 20px;">
        <template slot="title-container">
            <div class="title">
                {{ $t('trials:readOrder:title') }}
            </div>
        </template>

        <template slot="search-container">
            <el-form :inline="true">
                <!-- 是否加急 -->
                <el-form-item style="margin-bottom: 10px" :label="$t('trials:readOrder:table:isUrgent')">
                    <el-select v-model="searchData.IsUrgent" clearable style="width: 120px">
                        <el-option v-for="item of $d.YesOrNo" :key="'IsUrgent' + item.label" :value="item.value"
                            :label="item.label" />
                    </el-select>
                </el-form-item>
                <!-- 临床数据是否完备 -->
                <el-form-item style="margin-bottom: 10px"
                    :label="$t('trials:readOrder:table:completeClinicalDataEnum')">
                    <el-select v-model="searchData.CompleteClinicalDataEnum" clearable style="width: 120px">
                        <el-option v-for="item of $d.CompleteClinicalDataEnum"
                            :key="'CompleteClinicalDataEnum' + item.label" :value="item.value" :label="item.label" />
                    </el-select>
                </el-form-item>
                <!-- 中心编号 -->
                <el-form-item :label="$t('trials:readOrder:table:siteCode')">
                    <el-select v-model="searchData.TrialSiteId" clearable filterable style="width: 120px">
                        <el-option v-for="(item, index) of siteOptions" :key="index" :label="item.TrialSiteCode"
                            :value="item.TrialSiteId" />
                    </el-select>
                </el-form-item>
                <!-- 受试者编号 -->
                <el-form-item :label="$t('trials:readOrder:table:subjectCode')">
                    <el-input v-model="searchData.SubjectCode" style="width: 100px" />
                </el-form-item>
                <!-- 任务名称 -->
                <el-form-item style="margin-bottom: 10px" :label="$t('trials:readOrder:table:taskName')">
                    <el-input v-model="searchData.TaskName" style="width: 100px" clearable />
                </el-form-item>
                <!-- 阅片人 -->
                <el-form-item style="margin-bottom: 10px" :label="$t('trials:readOrder:table:reader')">
                    <el-select v-model="searchData.DoctorUserId" style="width: 120px">
                        <el-option v-for="item of DoctorUserList" :key="'DoctorUserId' + item.DoctorUserId"
                            :value="item.DoctorUserId" :label="`${item.UserName}(${item.FullName})`" />
                    </el-select>
                </el-form-item>
                <!-- 阅片标准 -->
                <el-form-item style="margin-bottom: 10px" :label="$t('trials:readOrder:table:criterionName')">
                    <el-select v-model="searchData.TrialReadingCriterionId" style="width: 120px">
                        <el-option v-for="item of trialCriterionList"
                            :key="'TrialReadingCriterionId' + item.TrialReadingCriterionId"
                            :value="item.TrialReadingCriterionId" :label="item.TrialReadingCriterionName" />
                    </el-select>
                </el-form-item>
                <!-- 分配时间 -->
                <el-form-item style="margin-bottom: 10px" :label="$t('trials:readOrder:table:assignTime')">
                    <el-date-picker v-model="timeList" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                        :default-time="['00:00:00', '23:59:59']" @change="changeTimeList" />
                </el-form-item>
                <el-form-item style="margin-bottom: 10px">
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                        {{ $t('common:button:search') }}
                    </el-button>
                    <el-button type="primary" icon="el-icon-refresh-left" @click="handleReset">
                        {{ $t('common:button:reset') }}
                    </el-button>
                    <!--导出-->
                    <el-button type="primary" icon="el-icon-download" @click="handleExport">
                        {{ $t('common:button:export') }}
                    </el-button>
                    <!-- 随机排序 -->
                    <el-button type="primary" @click="randomOrder"
                        :disabled="!searchData.TrialReadingCriterionId || !searchData.DoctorUserId" v-if="!isAdmin">
                        {{ $t('trials:readingTracking:button:order') }}
                    </el-button>
                </el-form-item>
            </el-form>
        </template>
        <template slot="main-container">
            <el-table v-adaptive="{ bottomOffset: 60 }" v-loading="loading" :data="list" stripe height="100"
                @sort-change="handleSortChange">
                <!-- 是否加急 -->
                <el-table-column prop="IsUrgent" :label="$t('trials:readOrder:table:isUrgent')" min-width="120"
                    sortable="custom" align="center" style="position: relative">
                    <template slot-scope="scope">
                        <el-tooltip placement="top">
                            <div slot="content">
                                <span>{{
                                    `${$t('trials:readOrder:label:taskUrgentType')}${$fd(
                                        'TaskUrgentType',
                                        scope.row.TaskUrgentType
                                    )}`
                                }}</span><br />
                                <span>{{
                                    scope.row.TaskUrgentRemake
                                        ? `${$t('trials:readOrder:label:taskUrgentRemake')}${scope.row.TaskUrgentRemake
                                        }`
                                        : ''
                                }}</span>
                            </div>
                            <div>
                                <el-button :disabled="!(
                                    !scope.row.TaskState &&
                                    (scope.row.ReadingTaskState === 0 ||
                                        scope.row.ReadingTaskState === 1)
                                ) || !scope.row.IsCanEditUrgentState
                                    " v-if="scope.row.IsUrgent" type="danger" size="mini">{{
                                        $fd('YesOrNo', scope.row.IsUrgent) }}</el-button>
                            </div>
                        </el-tooltip>
                        <el-button :disabled="!(
                            !scope.row.TaskState &&
                            (scope.row.ReadingTaskState === 0 ||
                                scope.row.ReadingTaskState === 1)
                        ) || !scope.row.IsCanEditUrgentState
                            " v-if="!scope.row.IsUrgent" type="primary" size="mini">{{
                                $fd('YesOrNo', scope.row.IsUrgent) }}</el-button>
                    </template>
                </el-table-column>
                <!-- 临床数据是否完备 -->
                <el-table-column prop="CompleteClinicalDataEnum"
                    :label="$t('trials:readOrder:table:completeClinicalDataEnum')" min-width="160"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.CompleteClinicalDataEnum === -1">
                            {{
                                $fd(
                                    'CompleteClinicalDataEnum',
                                    scope.row.CompleteClinicalDataEnum
                                )
                            }}
                        </span>
                        <el-button type="text" v-else>
                            {{
                                $fd(
                                    'CompleteClinicalDataEnum',
                                    scope.row.CompleteClinicalDataEnum
                                )
                            }}
                        </el-button>
                    </template>
                </el-table-column>
                <!-- 中心编号 -->
                <el-table-column prop="TrialSiteCode" :label="$t('trials:readOrder:table:siteCode')" min-width="100"
                    sortable="custom" show-overflow-tooltip />
                <!-- 受试者编号 -->
                <el-table-column prop="SubjectCode" :label="$t('trials:readOrder:table:subjectCode')" min-width="120"
                    sortable="custom" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="
                            scope.row.BlindSubjectCode &&
                            scope.row.BlindSubjectCode !== scope.row.SubjectCode
                        ">
                            {{ `${scope.row.SubjectCode}/${scope.row.BlindSubjectCode}` }}
                        </span>
                        <span v-else>{{ scope.row.SubjectCode }}</span>
                    </template>
                </el-table-column>
                <!-- 任务名称 -->
                <el-table-column prop="VisitTaskNum" :label="$t('trials:readOrder:table:taskName')" min-width="140"
                    sortable="custom" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="
                            scope.row.TaskBlindName &&
                            scope.row.TaskName !== scope.row.TaskBlindName
                        ">
                            {{ `${scope.row.TaskName}/${scope.row.TaskBlindName}` }}
                        </span>
                        <span v-else>{{ scope.row.TaskName }}</span>
                    </template>
                </el-table-column>
                <!-- 阅片人 -->
                <el-table-column prop="UserName" :label="$t('trials:readOrder:table:reader')" min-width="130"
                    sortable="custom" show-overflow-tooltip>
                    <template v-if="scope.row.UserName" slot-scope="scope">
                        <span>{{ scope.row.UserName }}({{ scope.row.FullName }})</span>
                    </template>
                </el-table-column>
                <!-- 阅片标准 -->
                <el-table-column prop="TrialReadingCriterionName" :label="$t('trials:readOrder:table:criterionName')"
                    min-width="180" sortable="custom" show-overflow-tooltip />
                <!-- 分配时间 -->
                <el-table-column prop="AllocateTime" :label="$t('trials:readOrder:table:assignTime')" min-width="180"
                    sortable="custom" show-overflow-tooltip />
                <!-- 阅片序号 -->
                <el-table-column prop="RandomOrder" :label="$t('trials:readOrder:table:randomOrder')" min-width="180"
                    sortable="custom" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.RandomOrder"
                            @change="(value, old) => handleChange(scope.row, value, old)" :min="0" style="width: 150px;"
                            v-if="scope.row.ReadingTaskState !== 1 && !isAdmin"></el-input-number>
                        <span v-else>{{ scope.row.RandomOrder }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
                @pagination="getList" />
        </template>
    </BaseContainer>
</template>
<script>
import { getTrialSiteSelect } from '@/api/trials'
import {
    getTrialCriterionList,
    getReadingTaskList,
    getDoctorUserSelectList,
    setRandomTaskOrder
} from '@/api/trials/reading'
import { getReadingTaskList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
const searchDataDefault = () => {
    return {
        PageIndex: 1,
        PageSize: 20,
        Asc: true,
        SortField: 'RandomOrder',
        TrialId: null,
        TrialSiteId: null,
        SubjectId: null,
        SubjectCode: null,
        IsUrgent: null,
        TaskName: null,
        TaskState: null,
        DoctorUserId: null,
        ReadingCategory: null,
        TaskAllocationState: null,
        BeginAllocateDate: null,
        EndAllocateDate: null,
        ReadingTaskState: null,
        CompleteClinicalDataEnum: null,
        BeginSignTime: null,
        EndSignTime: null,
        IsEffect: true,
        TrialReadingCriterionId: null,
        IsRandomOrderList: true
        // ArmEnum: null
    }
}
export default {
    name: 'ReadOrder',
    components: {
        BaseContainer,
        Pagination,
    },
    data() {
        return {
            searchData: searchDataDefault(),
            exportVisible: false,
            list: [],
            siteOptions: [],
            total: 0,
            SubjectAssignListTotal: 0,
            loading: false,
            trialCriterionList: [],
            DoctorUserList: [],
            timeList: []
        }
    },
    created() {
        if (!this.hasPermi(['role:pm', 'role:apm', 'role:admin'])) return this.$router.replace("/login")
    },
    computed: {
        isAdmin() {
            return !!this.hasPermi(['role:admin'])
        }
    },
    mounted() {
        this.getSite()
        Promise.all([this.getDoctorUserSelectList(), this.getTrialCriterionList()]).then(() => {
            this.getList()
        })

    },
    beforeDestroy() {
        if (this.openWindow) {
            this.openWindow.close()
        }
    },
    methods: {
        // 手动设置排序序号
        async handleChange(row, value, old) {
            try {
                if (!this.searchData.DoctorUserId || !this.searchData.TrialReadingCriterionId) return false
                if (!value) throw this.$t('trials:readOrder:message:min1')
                let data = {
                    TrialId: this.$route.query.trialId,
                    TrialReadingCriterionId: this.searchData.TrialReadingCriterionId,
                    DoctorUserId: this.searchData.DoctorUserId,
                    IsAutoSet: false,
                    SetList: [
                        { Id: row.Id, RandomOrder: value }
                    ]
                }
                this.loading = true;
                let res = await setRandomTaskOrder(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                } else {
                    row.RandomOrder = old
                }
            } catch (err) {
                row.RandomOrder = old
                console.log(err)
                this.$message.warning(err)
                this.getList()
                this.loading = false
            }
        },
        // 随机排序
        async randomOrder() {
            try {
                if (!this.searchData.DoctorUserId || !this.searchData.TrialReadingCriterionId) return false
                let data = {
                    TrialId: this.$route.query.trialId,
                    TrialReadingCriterionId: this.searchData.TrialReadingCriterionId,
                    DoctorUserId: this.searchData.DoctorUserId,
                    IsAutoSet: true,
                    SetList: []
                }
                this.loading = true;
                let res = await setRandomTaskOrder(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                }
            } catch (err) {
                console.log(err)
                this.loading = false
            }
        },
        async handleExport() {
            this.loading = true
            try {
                await getReadingTaskList_Export(this.searchData)
                this.loading = false
            } catch (e) {
                this.loading = false
            }
        },
        getTrialCriterionList() {
            return new Promise((resolve, reject) => {
                getTrialCriterionList(this.$route.query.trialId, true)
                    .then((res) => {
                        this.trialCriterionList = res.Result
                        if (this.trialCriterionList.length > 0) {
                            this.searchData.TrialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
                        }
                        resolve()
                    })
                    .catch(() => { reject() })
            })
        },
        getDoctorUserSelectList() {
            return new Promise((resolve, reject) => {
                getDoctorUserSelectList(this.$route.query.trialId).then((res) => {
                    this.DoctorUserList = res.Result
                    if (this.DoctorUserList.length > 0) {
                        this.searchData.DoctorUserId = this.DoctorUserList[0].DoctorUserId
                    }
                    resolve()
                }).catch(() => { reject() })
            })

        },
        getList() {
            if (!this.searchData.DoctorUserId || !this.searchData.TrialReadingCriterionId) return false
            this.searchData.TrialId = this.$route.query.trialId
            this.loading = true
            getReadingTaskList(this.searchData)
                .then((res) => {
                    this.loading = false
                    this.list = []
                    this.$nextTick(() => {
                        this.list = res.Result.CurrentPageData
                        this.total = res.Result.TotalCount
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        },
        handleSearch() {
            this.searchData.PageIndex = 1
            this.getList()
        },
        handleReset() {
            let TrialReadingCriterionId = this.searchData.TrialReadingCriterionId
            let DoctorUserId = this.searchData.DoctorUserId
            this.searchData = searchDataDefault()
            this.searchData.DoctorUserId = DoctorUserId
            this.searchData.TrialReadingCriterionId = TrialReadingCriterionId
            this.timeList = []
            this.getList()
        },
        getSite() {
            getTrialSiteSelect(this.$route.query.trialId).then((res) => {
                this.siteOptions = res.Result
            })
        },
        changeTimeList() {
            if (this.timeList) {
                this.searchData.BeginAllocateDate = this.timeList[0]
                this.searchData.EndAllocateDate = this.timeList[1]
            } else {
                this.searchData.BeginAllocateDate = null
                this.searchData.EndAllocateDate = null
            }
        },
        // 排序
        handleSortChange(column) {
            if (column.order === 'ascending') {
                this.searchData.Asc = true
            } else {
                this.searchData.Asc = false
            }
            this.searchData.SortField = column.prop
            this.searchData.PageIndex = 1
            this.getList()
        },
    },
}
</script>
<style lang="scss" scoped>
.title {
    line-height: 40px;
    font-weight: bold;
    margin-bottom: 10px;
}
</style>
