<template>
  <div class="page-channel p-6">
    <div class="h-full w-full flex">
      <div class="mr-2">
        <el-card shadow="never" class="h-full">
          <template #header>
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <div>服务类别</div>
              </div>
              <el-button
                type="primary"
                :icon="Plus"
                class="ml-2"
                @click="
                  editVisible = true;
                  editForm = {
                    id: undefined,
                    name: '',
                    content: ''
                  };
                "
                >添加服务类别</el-button
              >
            </div>
          </template>
          <div>
            <el-table
              :data="state.list"
              class="w-full"
              :show-header="false"
              max-height="85vh"
              @row-click="editRow"
            >
              <el-table-column prop="name" label="姓名">
                <template #default="{ row }">
                  <div
                    class="p-2 hover:bg-gray-50 cursor-pointer rounded"
                    :class="{
                      'bg-gray-10 border-r-4 border-blue-500 color: text-blue-500':
                        currentValue?.id == row.id
                    }"
                  >
                    <h3>{{ row.name }}</h3>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              background
              class="justify-end mt-4"
              layout="total, prev, pager, next"
              :page-size="10"
              :total="state.total"
              @change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
      <div class="flex-1 h-full">
        <div v-if="currentValue?.id" class="h-full flex flex-col bg-white">
          <div class="p-4 border-b border-solid border-gray-200">
            <div class="flex items-center justify-between">
              <div>
                <h4>{{ currentValue.name }}</h4>
                <el-text>使用范围：{{ currentValue.content }}</el-text>
              </div>
              <div class="ml-8">
                <el-button type="primary" :icon="Edit" link @click="handleEdit"
                  >编辑</el-button
                >
                <el-popconfirm
                  title="确定要删除这个机构吗？"
                  width="300"
                  @confirm="handleDelete"
                >
                  <template #reference>
                    <el-button type="danger" :icon="Delete" link
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </div>
          <div class="flex-1 p-4 overflow-y-auto">
            <div class="flex items-center">
              <el-button type="primary" @click="showEditCheckItem(null)"
                >+添加服务项目</el-button
              >
            </div>
            <el-table
              :data="checkItem.list"
              border
              class="mt-4"
              v-loading="checkItem.loading"
              element-loading-text="加载中..."
            >
              <el-table-column label="检查项目名称" prop="name" />
              <el-table-column label="检查项目类型">
                <template #default="{ row }">
                  {{ ["检验", "检查"][row.type - 1] }}
                </template>
              </el-table-column>
              <el-table-column label="检查内容">
                <template #default="{ row }">
                  <div>
                    {{ row.checkItems.map(v => v.name).join() }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    :icon="Edit"
                    link
                    @click="showEditCheckItem(row)"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    title="确定要删除这个检查项目吗？"
                    width="300"
                    @confirm="handleDeleteCheckItem(row)"
                  >
                    <template #reference>
                      <el-button type="danger" :icon="Delete" link
                        >删除</el-button
                      >
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column></el-table
            >

            <el-pagination
              background
              class="justify-end mt-4"
              layout="total, prev, pager, next"
              v-model:current-page="checkItem.query.page"
              :total="checkItem.total"
              @current-change="
                p => {
                  checkItem.query.page = p;
                  getCheckItemList();
                }
              "
            />
          </div>
        </div>
        <el-card shadow="never" class="h-full" v-else>
          <div>
            <el-empty />
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog title="服务类别设置" v-model="editVisible">
      <div>
        <el-form ref="formRef" :model="editForm" label-width="120px">
          <el-form-item
            label="类别名称："
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入类别名称',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="editForm.name"
              placeholder="请输入类别名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="类别说明：" prop="content">
            <el-input
              v-model="editForm.content"
              type="textarea"
              :rows="10"
              placeholder="输入说明信息"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditTemplate">保 存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="editCheckItem.visible"
      title="服务项目设置"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      destroy-on-close
      width="80%"
    >
      <el-form ref="formCheckItemRef" :model="editCheckItem.row">
        <el-form-item
          label="服务项目名称"
          prop="name"
          :rules="[
            {
              required: true,
              message: '请输入服务项目名称',
              trigger: 'blur'
            }
          ]"
        >
          <el-input
            v-model="editCheckItem.row.name"
            placeholder="请输入服务项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="服务形式"
          prop="type"
          :rules="[
            {
              required: true,
              message: '请选择服务形式',
              trigger: 'blur'
            }
          ]"
        >
          <el-radio-group v-model="editCheckItem.row.type">
            <el-radio :label="0">按次服务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="服务方式"
          prop="mode"
          :rules="[
            {
              required: true,
              message: '请选择服务方式',
              trigger: 'blur'
            }
          ]"
        >
          <el-radio-group v-model="editCheckItem.row.mode">
            <el-radio :label="0">线上/线下服务</el-radio>
            <el-radio :label="1">电话服务</el-radio>
            <el-radio :label="2">综合服务</el-radio>
            <el-radio :label="3">专家服务</el-radio>
            <el-radio :label="4">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务内容描述">
          <el-input
            v-model="editCheckItem.row.content"
            type="textarea"
            rows="10"
            placeholder="输入服务项目内容描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editCheckItem.visible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditCheckItem">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog title="" v-model="state.massAddvisible" width="50%">
      <div>
        <el-input
          type="textarea"
          v-model="state.content"
          :rows="18"
          placeholder="输入检查内容，多个检查内容之间用中文输入法下的分号或顿号区隔"
        />
      </div>
      <template #footer>
        <el-button @click="state.massAddvisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMassAddContent"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";

import { request, unique } from "@/utils";
import { ElMessage } from "element-plus";

const state = reactive({
  visible: false,
  list: [],
  total: 0,
  rowData: {},
  content: "",
  massAddvisible: false
});
const query = reactive({
  title: "",
  page: 1
});
const formCheckItemRef = ref();

const onSearch = () => {
  query.page = 1;
  getList();
};
const getList = async () => {
  const { data } = await request.get(
    "walletService/mechanism/membershipCard/serviceCategory/paginate",
    { params: query }
  );
  state.list = data.list;
  state.total = data.total;
  if (query.page == 1 && data.list[0]) {
    editRow(data.list[0]);
  }
};
const handleCurrentChange = page => {
  query.page = page;
  getList();
};
const handleDelete = async () => {
  const { message } = await request.post(
    `dataService/schemeManage/medicalCheck/hospital/delete`,
    {
      id: currentValue.value.id
    }
  );
  ElMessage.success(message);
  getList();
};
getList();

const editRow = row => {
  currentValue.value = row;
  checkItem.query.id = row.id;
  getCheckItemList();
};
const editForm = ref({
  id: "",
  name: "",
  content: ""
});
const editVisible = ref(false);
const currentValue = ref({
  id: ""
});

const handleEdit = () => {
  editForm.value = currentValue.value;
  editVisible.value = true;
};
const saveEditTemplate = async () => {
  const { message } = await request.post(
    `walletService/mechanism/membershipCard/serviceCategory${
      editForm.value.id ? "/update" : ""
    }`,
    editForm.value
  );
  ElMessage.success(message);
  editVisible.value = false;
  if (!editForm.value.id) {
    onSearch();
  }
  getList();
};

const checkItem = reactive({
  query: {
    id: "",
    name: "",
    page: 1
  },
  list: [],
  total: 0,
  rowData: {}
});
const editCheckItem = reactive({
  visible: false,
  systemCheckList: [],
  row: {
    id: undefined,
    name: "",
    systemCheck: "",
    type: 1,
    checkItems: []
  }
});

const getCheckItemList = async () => {
  const { data } = await request.get(
    "walletService/mechanism/membershipCard/serviceCategory",
    { params: checkItem.query }
  );
  checkItem.list = data.list || [];
  checkItem.total = data.total;
};
const showEditCheckItem = async row => {
  if (row) {
    editCheckItem.row = row;
  } else {
    editCheckItem.row = {
      id: undefined,
      name: "",
      type: 0,
      mode: 0,
      content: ""
    };
  }
  editCheckItem.visible = true;
};
const saveEditCheckItem = async () => {
  formCheckItemRef.value.validate(async valid => {
    if (!valid) return;
    // return
    const { message } = await request.post(
      `walletService//mechanism/membershipCard/serviceItem${
        editCheckItem.row.id ? "/update" : ""
      }`,
      {
        categoryId: currentValue.value.id,
        ...editCheckItem.row,
        id: checkItem.query.id
      }
    );
    ElMessage.success(message);
    editCheckItem.visible = false;
    getCheckItemList();
  });
};
const handleDeleteCheckItem = async row => {
  const { message } = await request.post(
    `dataService/schemeManage/medicalCheck/item/delete`,
    {
      id: row.id,
      id: checkItem.query.id
    }
  );
  ElMessage.success(message);
  getCheckItemList();
};

const handleMassAddContent = () => {
  try {
    const contentArray = state.content
      .replaceAll(";", "、")
      .split("、")
      .filter(v => v);

    const array = [];
    contentArray.map(v => {
      array.push({
        name: v,
        unit: "",
        scope: "",
        sort: "",
        node: "",
        nodes: [],
        matchProject: [],
        indicators: []
      });
    });
    // 去重
    editCheckItem.row.checkItems = unique(
      [...editCheckItem.row.checkItems, ...array],
      "name"
    );
  } catch (error) {
    ElMessage.error(error);
  } finally {
    state.massAddvisible = false;
  }
};
</script>
<style lang="scss">
.el-scrollbar__view {
  height: 100%;
  .main-content.page-channel {
    height: 100%;
    margin: 0;
  }
}
::v-deep {
  .el-card__header {
    height: 74px;
  }
  .el-table .el-table__body tr:hover > td {
    background-color: transparent;
  }
}
</style>
