<template>
  <PageWrapper>
    <Card
      :bordered="false"
      :active-tab-key="activeKey"
      :tab-list="tabList"
      style="height: 800px"
      @tabChange="
        key => {
          activeKey = key;
        }
      "
    >
      <p :key="0" v-if="activeKey == 0">
        <Row>
          <Col :span="6">
            <Card title="病区属性" style="height: 680px">
              <template #extra
                ><Button
                  shape="circle"
                  v-auth="['bizSys:wardProperties:add']"
                  @click="handleAddAttr"
                  ><Icon icon="icon-plus|iconfont" :size="14" /></Button
              ></template>
              <Row>
                <div class="type-title">阴性</div>
              </Row>
              <Row v-for="item in attributeFeminineList" :key="item.key" style="margin: 4px 0">
                <Tag
                  class="attrs"
                  closable
                  @close="handleDeleteAttr(item.key)"
                  @click="handleSelectWard(item)"
                  :value="item.key"
                  >{{ item.label }}
                </Tag>
              </Row>
              <Row>
                <div class="type-title">阳性</div>
              </Row>
              <Row v-for="item in attributePositiveList" :key="item.key" style="margin: 4px 0">
                <Tag
                  class="attrs"
                  closable
                  @close="handleDeleteAttr(item.key)"
                  @click="handleSelectWard(item)"
                  :value="item.key"
                  >{{ item.label }}</Tag
                >
              </Row>
            </Card>
          </Col>
          <Col :span="1" />
          <Col :span="17">
            <Card title="病区信息" style="height: 680px">
              <template #extra
                ><Button shape="circle" v-auth="['bizSys:wardInfo:add']" @click="handleAddInfo"
                  ><Icon icon="icon-plus|iconfont" :size="14" /></Button
              ></template>
              <BasicTable @register="registerTable">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'disable'">
                    <Tag :color="formatDictColor(disableOptions, record.disable)">
                      {{ formatDictValue(disableOptions, record.disable) }}
                    </Tag>
                  </template>
                  <template v-if="column.key === 'action'">
                    <TableAction
                      :actions="[
                        {
                          auth: 'bizSys:wardInfo:edit',
                          icon: 'icon-xt-details_edit_default|iconfont',
                          tooltip: '编辑',
                          onClick: handleEdit.bind(null, record),
                        },
                        {
                          auth: 'bizSys:wardInfo:status',
                          icon: 'icon-xt-details_delete_default|iconfont',
                          tooltip: '停用',
                          ifShow: record.disable == 0,
                          popConfirm: {
                            title: '是否确认停用',
                            placement: 'left',
                            confirm: handleChangeState.bind(null, record),
                          },
                        },
                        {
                          auth: 'bizSys:wardInfo:status',
                          icon: 'icon-plus|iconfont',
                          tooltip: '启用',
                          label: '',
                          ifShow: record.disable == 1,
                          popConfirm: {
                            title: '是否确认启用',
                            placement: 'left',
                            confirm: handleChangeState.bind(null, record),
                          },
                        },
                      ]"
                    />
                  </template>
                </template>
              </BasicTable>
            </Card>
          </Col>
        </Row>
      </p>
      <p :key="1" v-else>
        <Row>
          <Col :span="6">
            <Card title="工作日配置" style="height: 680px">
              <template #extra
                ><Button shape="circle" v-auth="['bizSys:workday:edit']" @click="handleEditWorkDay">
                  <Icon icon="icon-xt-details_edit_default|iconfont" :size="14" /></Button
              ></template>
              <Row v-for="(item, index) in workDays" :key="index">
                <div class="wrak-day">{{ item.label }}</div>
              </Row>
            </Card>
          </Col>
          <Col :span="1" />
          <Col :span="17">
            <Card title="班次配置" style="height: 680px">
              <template #extra
                ><Button v-auth="['bizSys:wardInfo:add']" @click="handleAddSailing" shape="circle"
                  ><Icon icon="icon-xt-details_edit_default|iconfont" :size="14" /></Button
              ></template>
              <BasicTable @register="registerSailingsTable">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'disable'">
                    <Tag :color="formatDictColor(disableOptions, record.disable)">
                      {{ formatDictValue(disableOptions, record.disable) }}
                    </Tag>
                  </template>
                  <template v-if="column.key === 'action'">
                    <TableAction
                      :actions="[
                        {
                          auth: 'bizSys:wardInfo:edit',
                          icon: 'icon-xt-details_edit_default|iconfont',
                          tooltip: '编辑',
                          label: '',
                          onClick: handleEdit.bind(null, record),
                        },
                        {
                          auth: 'bizSys:wardInfo:status',
                          icon: 'icon-minus-square|iconfont',
                          tooltip: '停用',
                          label: '',
                          color: 'error',
                          ifShow: record.disable == 0,
                          popConfirm: {
                            title: '是否确认停用',
                            placement: 'left',
                            confirm: handleChangeState.bind(null, record),
                          },
                        },
                        {
                          auth: 'bizSys:wardInfo:status',
                          icon: 'icon-plus|iconfont',
                          tooltip: '启用',
                          label: '',
                          ifShow: record.disable == 1,
                          color: 'error',
                          popConfirm: {
                            title: '是否确认启用',
                            placement: 'left',
                            confirm: handleChangeState.bind(null, record),
                          },
                        },
                      ]"
                    />
                  </template>
                </template>
              </BasicTable>
            </Card>
          </Col>
        </Row>
      </p>
    </Card>
  </PageWrapper>
  <WardTypeFormModal @register="registerWardTypeModal" @success="handleWardTypeSuccess" />
  <WardInfoFormModal @register="registerWardInfoModal" @success="handleWardInfoSuccess" />
  <WorkDayFormModal @register="registerWorkDayModal" @success="handleWorkDaySuccess" />
  <SailingEdit @register="registerSailingEditModal" @success="handleSailingSuccess" />
</template>

<script lang="ts" setup>
  import { onBeforeMount, ref } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { Button, Card, Row, Col, Tag } from 'ant-design-vue';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { wardInfoColumns, sailingsColumns } from './data';
  import WardTypeFormModal from './wardTypeFormModal.vue';
  import WardInfoFormModal from './wardInfoFormModal.vue';
  import WorkDayFormModal from './workDayFormModal.vue';
  import SailingEdit from './sailingsEditFormModal.vue';
  import { getWardInfo, changeStatus } from '/@/api/biz/management/wardInfo';
  import { getAttrList, deleteWardType } from '/@/api/biz/management/wardType';
  import { getWorkingDay, getSailings } from '/@/api/biz/management/working';
  import { useModal } from '/@/components/Modal';
  import { listDictModel } from '/@/api/common';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { formatDictColor, formatDictValue } from '/@/utils';
  const { createConfirm, createMessage } = useMessage();
  const tabList = ref([
    { key: 0, tab: '病区管理', type: 'WARD' },
    { key: 1, tab: '工作日班次', type: 'WORK' },
  ]);
  const activeKey = ref(0);
  const attributePositiveList = ref([]); // 阳性列表
  const attributeFeminineList = ref([]); // 阴性列表
  const workDays = ref([]);
  const disableOptions = ref();
  onBeforeMount(async () => {
    disableOptions.value = await listDictModel({ dictCode: 'sys_disable_type' });
    await getWardType();
    await getWordDay();
  });
  const [registerTable, { reload }] = useTable({
    api: getWardInfo,
    rowKey: 'id',
    columns: wardInfoColumns,
    showIndexColumn: false,
    formConfig: {
      labelWidth: 120,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    useSearchForm: false,
    bordered: true,
    actionColumn: {
      width: 320,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    sortFn: handleSortFn,
  });

  const [registerSailingsTable, { reload: SailingsReload }] = useTable({
    api: getSailings,
    columns: sailingsColumns,
    showIndexColumn: false,
    formConfig: {
      labelWidth: 120,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 8 },
    },
    useSearchForm: false,
    bordered: true,
  });

  const [registerWardTypeModal, { openModal: openWardTypeModal }] = useModal();
  const [registerWardInfoModal, { openModal: openWardInfoModal }] = useModal();
  const [registerWorkDayModal, { openModal: openWorkDayModal }] = useModal();
  const [registerSailingEditModal, { openModal: openSailingModal }] = useModal();
  const tableSort = ref([
    {
      field: 'sort',
      direction: 'ASC',
    },
  ]);
  const selectType = ref();

  // 方法区
  // 获取病区信息前事件
  function handleBeforeFetch(params) {
    return { ...params, propertiesId: selectType.value, orders: tableSort.value };
  }

  function handleSortFn() {}
  // 打开新增属性方法
  function handleAddAttr() {
    openWardTypeModal(true, {
      isUpdate: false,
    });
  }
  // 打开删除属性方法
  async function handleDeleteAttr(id) {
    createConfirm({
      content: '你确定要删除?',
      iconType: 'warning',
      onOk: async () => {
        await deleteWardType([id]);
        createMessage.success('属性删除成功！');
        await getWardType();
      },
      onCancel: async () => {
        attributePositiveList.value = [];
        attributeFeminineList.value = [];
        await getWardType();
      },
    });
  }
  //打开新增病区信息方法
  function handleAddInfo() {
    openWardInfoModal(true, {
      isUpdate: false,
    });
  }

  //打开编辑工作日方法
  function handleEditWorkDay() {
    openWorkDayModal(true, {
      record: workDays.value,
      isUpdate: true,
    });
  }

  // 打开编辑病区信息方法
  function handleEdit(record: Recordable) {
    openWardInfoModal(true, {
      record,
      isUpdate: true,
    });
  }
  // 停用启用病区方法
  async function handleChangeState(record) {
    const notes = record.disable == 0 ? '停用' : '启用';
    await changeStatus(record.id);
    createMessage.success('病区' + notes + '成功！');
    reload();
  }

  // 保存成功回调事件
  async function handleWardTypeSuccess() {
    await getWardType();
  }

  function handleWardInfoSuccess() {
    reload();
    SailingsReload();
  }

  async function getWardType() {
    const attrList = await getAttrList();
    attributePositiveList.value = []; // 阳性列表
    attributeFeminineList.value = [];
    attrList.forEach(item => {
      if (item.positive) {
        attributePositiveList.value.push({ label: item.name, key: item.id });
      } else {
        attributeFeminineList.value.push({ label: item.name, key: item.id });
      }
    });
  }
  // 通过病区属性搜索病区信息
  function handleSelectWard(e) {
    selectType.value = e.key;
    reload();
  }

  // 获取工作日
  async function getWordDay() {
    const res = await getWorkingDay();
    const workDay = [];
    Object.keys(res).forEach((value, index) => {
      if (res[value]) {
        switch (value) {
          case 'monday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周一',
            });
            break;
          }

          case 'tuesday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周二',
            });
            break;
          }

          case 'wednesday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周三',
            });
            break;
          }

          case 'thursday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周四',
            });
            break;
          }

          case 'friday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周五',
            });
            break;
          }

          case 'saturday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周六',
            });
            break;
          }

          case 'sunday': {
            workDay.push({
              name: value,
              key: index,
              value: res[value],
              label: '周日',
            });
            break;
          }
        }
      }
    });
    workDays.value = workDay;
  }
  // 新增班次
  function handleAddSailing() {
    openSailingModal(true, {});
  }

  async function handleWorkDaySuccess() {
    await getWordDay();
  }

  async function handleSailingSuccess() {
    await SailingsReload();
  }
</script>

<style lang="less" scoped>
  ::v-deep(.ant-card-head) {
    background-color: #f6f8fa !important;
  }

  .type-title {
    font-size: 14px;
    font-weight: bold;
    color: #000a18;
  }

  .attrs {
    background: #fff !important;
    height: 32px !important;
    line-height: 32px !important;
    font-weight: 400 !important;
    color: #17233d !important;
    font-size: 14px !important;
    border-radius: 4px !important;
    border: 1px solid #c2ccd4 !important;
  }

  .wrak-day {
    width: 28px;
    height: 20px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 14px;
    font-weight: 500;
    color: #000a18;
    line-height: 20px;
  }

  ::v-deep(.ant-btn-link) {
    color: rgb(61 65 85 / 100%);
  }
</style>
