<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2023年4月10日 11:08:42
 */
import {
  AppointmentListAction,
  AppointmentChangeStatusAction,
  AppointmentChangeCountAction,
  $response, HospitalSelectListAction, AppointmentDeleteAction
} from '~/api'

import $router from '~/router'
import {onBeforeRouteUpdate} from "vue-router";
import {NSpace, NTag} from "naive-ui";

const default_page_options = {
  start_date: null,
  end_date: null,
  weeks: [1, 2, 3, 4, 5, 6, 7],
  hospital: null,
  status: 0,
  page: 1
}
const page_options = ref(JSON.parse(JSON.stringify(default_page_options)))
onBeforeRouteUpdate((to) => {
  routerChange(to.query)
})

const routerChange = (query) => {
  page_options.value = {
    start_date: query.start_date || default_page_options.start_date,
    end_date: query.end_date || default_page_options.end_date,
    weeks: (query.weeks || default_page_options.weeks.join(',')).split(',').map(Number),
    hospital: Number(query.hospital || default_page_options.hospital),
    status: Number(query.status) || default_page_options.status,
    page: Number(query.page) || default_page_options.page
  }
  appointment_active.value = []
  if (hospital_select_list.value.length === 0) {
    HospitalSelectList()
  } else {
    AppointmentList()
  }
}

onMounted(() => {
  routerChange($router.currentRoute.value.query)
})

const appointment_active = ref([])
const appointment_list = ref([])
const appointment_list_last_page = ref(0)

const AppointmentList = async () => {
  const response = await AppointmentListAction(page_options.value)
  $response(response, () => {
    appointment_list.value = response.data.data
    appointment_list_last_page.value = response.data.last_page
  })
}
const week_arr = ['一', '二', '三', '四', '五', '六', '日'];
const date_type_arr = ['info', 'success', 'error'];
const date_type_text_arr = ['普', '假', '班'];
const appointment_columns = [
  {
    type: 'selection'
  },
  {
    title: '日期',
    key: 'date',
    render(row) {
      let children = [h(
        'span',
        {},
        row.date
      )]
      if (row.date_type > 0) {
        children.push(h(
          NTag,
          {
            class: 'ml-2',
            size: 'small',
            type: date_type_arr[row.date_type]
          },
          {
            default: () => {
              return date_type_text_arr[row.date_type]
            }
          }
        ))
      }
      return children
    }
  },
  {
    title: '星期',
    key: 'week',
    render(row) {
      return `星期${week_arr[row.week - 1]}`
    }
  },
  {
    title: '开始时间',
    key: 'start_time'
  },
  {
    title: '结束时间',
    key: 'end_time'
  },
  {
    title: '停止预约时间',
    key: 'stop_time'
  },
  {
    title: '最大预约人数',
    key: 'max_count'
  },
  {
    title: '已预约人数',
    key: 'used_count'
  },
  {
    title: '已预约人数',
    key: 'date_type'
  },
  {
    title: '剩余数量',
    key: 'max_count',
    render(row) {
      let count = row.max_count - row.used_count
      return count > 0 ? count : 0
    }
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      return h(
        NTag,
        {
          type: row.status === 1 ? 'success' : 'error'
        },
        {
          default: () => {
            return row.status === 1 ? '可用' : '停用'
          }
        }
      )
    }
  }
]

const searchClick = () => {
  updatePage(1)
}
const updatePage = (page) => {
  page_options.value.page = page
  pagePush()
}
const pagePush = () => {
  $router.push({
    name: 'appointment-list',
    query: {
      ...page_options.value,
      weeks: page_options.value.weeks.join(',')
    }
  })
}

const hospital_select_list = ref([])
const HospitalSelectList = async () => {
  const response = await HospitalSelectListAction()
  $response(response, () => {
    hospital_select_list.value = response.data.list.map((item) => {
      return {
        label: item.name,
        value: item.id
      }
    })
    if (hospital_select_list.value.length && !page_options.value.hospital) {
      page_options.value.hospital = hospital_select_list.value[0].value
    }
    if (!!page_options.value.hospital) {
      AppointmentList()
    }
  })
}

const delete_show = ref(false)
const deleteShowClick = () => {
  if (appointment_active.value.length === 0) return window.$message().error('请选择一个计划')
  delete_show.value = true
}
const AppointmentDelete = async () => {
  const response = await AppointmentDeleteAction({
    ids: appointment_active.value
  })
  $response(response, () => {
    window.$message().success(response.message)
    delete_show.value = false
    appointment_active.value = []
    AppointmentList()
  })
}

const createClick = () => {
  $router.push({
    name: 'appointment-template'
  })
}
const change_status_show = ref(false)
const change_status = ref(1)
const changeStatusShowClick = () => {
  if (appointment_active.value.length === 0) return window.$message().error('请选择一个计划')
  let status = 1
  for (let i in appointment_list.value) {
    if (appointment_active.value.indexOf(appointment_list.value[i].id) !== -1) {
      status = appointment_list.value[i].status
    }
  }
  change_status.value = status
  change_status_show.value = true
}
const AppointmentChangeStatus = async () => {
  const response = await AppointmentChangeStatusAction({
    ids: appointment_active.value,
    status: change_status.value
  })
  $response(response, () => {
    change_status_show.value = false
    window.$message().success(response.message)
    AppointmentList()
  })
}

const change_count_show = ref(false)
const change_count = ref(1)
const changeCountShowClick = () => {
  if (appointment_active.value.length === 0) return window.$message().error('请选择一个计划')
  let max_count = 0
  for (let i in appointment_list.value) {
    if (appointment_active.value.indexOf(appointment_list.value[i].id) !== -1) {
      if (appointment_list.value[i].max_count > max_count) {
        max_count = appointment_list.value[i].max_count
      }
    }
  }
  change_count.value = max_count
  change_count_show.value = true
}
const AppointmentChangeCount = async () => {
  const response = await AppointmentChangeCountAction({
    ids: appointment_active.value,
    count: change_count.value
  })
  $response(response, () => {
    change_count_show.value = false
    window.$message().success(response.message)
    AppointmentList()
  })
}
</script>
<template>
  <div>
    <n-modal v-model:show="delete_show" preset="card" :style="{width: '400px'}" title="删除确认" :auto-focus="false"
             :bordered="false">
      <div>
        <n-space justify="center">
          <n-button @click="AppointmentDelete()" type="info">确定</n-button>
          <n-button @click="delete_show = false">取消</n-button>
        </n-space>
      </div>
    </n-modal>

    <n-modal v-model:show="change_status_show" preset="card" :style="{width: '400px'}" title="修改状态"
             :auto-focus="false" :bordered="false">
      <div>
        <div>
          <n-space align="center">
            <n-tag>
              <div class="form_tag_wrapper">状态</div>
            </n-tag>
            <n-select class="form_input_wrapper" v-model:value="change_status" :options="[
            {value:1,label:'可用'},
            {value:2,label:'停用'},
          ]"/>
          </n-space>
        </div>
        <n-space mt-2 justify="center">
          <n-button @click="AppointmentChangeStatus()" type="info">确定</n-button>
          <n-button @click="change_status_show = false">取消</n-button>
        </n-space>
      </div>
    </n-modal>

    <n-modal v-model:show="change_count_show" preset="card" :style="{width: '400px'}" title="修改数量"
             :auto-focus="false" :bordered="false">
      <div>
        <div>
          <n-space align="center">
            <n-tag>
              <div class="form_tag_wrapper">最大计划数量</div>
            </n-tag>
            <n-input-number class="form_input_wrapper" v-model:value="change_count"></n-input-number>
          </n-space>
        </div>
        <n-space mt-2 justify="center">
          <n-button @click="AppointmentChangeCount()" type="info">确定</n-button>
          <n-button @click="change_count_show = false">取消</n-button>
        </n-space>
      </div>
    </n-modal>

    <n-card title="预约计划">
      <div>
        <n-space align="center">
          <n-tag>
            <div class="form_tag_wrapper">医院</div>
          </n-tag>
          <n-select class="form_input_wrapper" v-model:value="page_options.hospital"
                    :options="hospital_select_list"/>
          <n-tag>
            <div class="form_tag_wrapper">开始日期</div>
          </n-tag>
          <n-date-picker v-model:formatted-value="page_options.start_date" type="date"/>
          <n-tag>
            <div class="form_tag_wrapper">结束日期</div>
          </n-tag>
          <n-date-picker v-model:formatted-value="page_options.end_date" type="date"/>
        </n-space>
        <n-space mt-2 align="center">
          <n-tag>
            <div class="form_tag_wrapper">状态</div>
          </n-tag>
          <n-radio-group v-model:value="page_options.status" name="status_radio">
            <n-space>
              <n-radio :value="0">全部</n-radio>
              <n-radio :value="1">可用</n-radio>
              <n-radio :value="2">停用</n-radio>
            </n-space>
          </n-radio-group>
          <n-tag>
            <div class="form_tag_wrapper">星期</div>
          </n-tag>
          <n-checkbox-group v-model:value="page_options.weeks">
            <n-space item-style="display: flex;">
              <n-checkbox v-for="(i,k) in week_arr" :key="k" :value="k+1" :label="`星期${i}`"/>
            </n-space>
          </n-checkbox-group>
          <n-button @click="searchClick()" type="info">搜索</n-button>
        </n-space>
        <n-space mt-2>
          <n-button @click="createClick()" type="success">新建</n-button>
          <n-button @click="deleteShowClick()" type="error">删除</n-button>
          <n-button @click="changeStatusShowClick()" type="info">修改状态</n-button>
          <n-button @click="changeCountShowClick()" type="info">修改数量</n-button>
        </n-space>
        <n-data-table mt-2 v-model:checked-row-keys="appointment_active" :columns="appointment_columns"
                      :row-key="row=>row.id" :data="appointment_list"/>
        <n-pagination v-if="appointment_list_last_page > 1" @update:page="updatePage" mt-2
                      v-model:page="page_options.page"
                      :page-count="appointment_list_last_page"/>
      </div>
    </n-card>
  </div>
</template>
<style scoped>

</style>
<route>
{"meta":{"title":"预约计划"}}
</route>

