<template>
  <div class="app-container">
    <page-search :searchFormConfig="searchFormConfig" @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick" />
    <page-content ref="pageContentRef" :contentTableConfig="contentTableConfig" pageName="/patient/patient"
      :isExport="false" @newBtnClick="handleNewData" @editBtnClick="handleEditData">

      <template #handler="{ row }">
        <el-button type="danger" size="small" link @click="joinBlacklist(row)">拉黑</el-button>
      </template>

      <template #otherHandler>
        <el-button type="primary" @click="batchLabels(1)">批量添加标签</el-button>
        <el-button type="danger" @click="batchLabels(0)">批量删除标签</el-button>
      </template>

      <template #patientId="{ row }">
        <el-button type="primary" link @click="buttonHandle(row.patientId)">{{ row.name || '未知' }}</el-button>
        <!-- <el-button type="primary" link>{{ row.name || '未知' }}</el-button> -->
      </template>
      <template #phoneNumber="{ row }">
        {{ row.phoneNumber && userDecryptToAsterisk(row.phoneNumber) }}
      </template>
      <template #patientStatus="{ row }">
        <el-tag v-if="row.patientStatus && statusMap[row.patientStatus]" :type="statusMap[row.patientStatus].color">{{
          statusMap[row.patientStatus].title }}</el-tag>
      </template>
      <template #patientSource="{ row }">
        <el-tag v-if="row.source && sourceMap[row.source]" :type="sourceMap[row.source].color">
          {{ sourceMap[row.source].title }}
        </el-tag>
      </template>
      <template #phoneStatus="{ row }">
        <el-tag v-if="row.phoneStatus && phoneStatusMap[row.phoneStatus]"
          :type="phoneStatusMap[row.phoneStatus].color">{{ phoneStatusMap[row.phoneStatus].title }}</el-tag>
      </template>

      <template #sex="{ row }">
        {{ sexMap[row.sex] ? sexMap[row.sex].title : '' }}
      </template>
      <template #labellist="{ row }" >
        <div v-if="row.labellist && row.labellist.length > 0">
          <el-tag  type="info" style="margin-left: 1px" :key="index" v-for="(item, index) in row.labellist">{{
            item.labelName }}</el-tag>
        </div>
      </template>



    </page-content>
    <page-modal :defaultInfo="defaultInfo" ref="pageModalRef" pageName="/patient/patient" :modalConfig="modalConfigRef"
      @submit="submit"></page-modal>

    <!-- 黑名单组件 -->
    <page-modal :defaultInfo="blackInfo" ref="blackModalRef" pageName="/patient/black" :modalConfig="blackModalConfig"
      :otherInfo="blackOtherInfo" @submit="blackSubmit"></page-modal>

    <el-dialog v-model="dialogFormVisible" :title="dialogFormTitle" width="500">
      <el-cascader ref="labelCascaderRef" class="w-full" v-model="selectTags"
                                :props="{ label: 'dictLabel', value: 'tagId' }" placeholder="请选择标签" :options="labels" filterable/>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="batchChangeTag">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent,onMounted } from 'vue'
import { useRouter } from 'vue-router';
import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'
import { setLabel, cancelLabel } from '@/api/patient/patient';
import { userDecryptToAsterisk } from '@/utils/aes'
import { getPageListData } from '@/api/main/system/system'
import { searchFormConfig } from './config/search.config'
import { contentTableConfig } from './config/content.config'
import { modalConfig } from './config/modal.config'
import { modalConfig as blackModalConfig} from '@/views/main/patientFile/patientblack/config/modal.config'
import { areaTrees } from "@/utils/area.js";
import { nations, patientStatus, sex, patientSource, phoneStatus } from "@/utils/commonDic.js";
import { ArrayToMap } from '@/utils/tools'

import { usePageSearch } from '@/hooks/use-page-search'
import { usePageModal } from '@/hooks/use-page-modal'
import { ElMessage, ElMessageBox } from 'element-plus'

export default defineComponent({
  name: 'PatientFileList',
  components: {
    PageSearch,
    PageContent,
    PageModal
  },
  setup() {
    let { proxy } = getCurrentInstance()

    onMounted(() => {
      console.log(proxy.$route, 'proxy.$route.query');
      getLabelsTree();
    })  
    const router = useRouter();
    const [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch()
    const activeNames = ref(['1'])
    const input2 = ref('')
    const iconFlag = ref(true)
    const form = ref({
      name: '',
      date1: '',
      date2: '',
      delivery: '',
      resource: '',
    })
    function buttonHandle(id) {
      console.log(id);
      router.push({
        path: '/patientFile/patientDetail',
        query: {
          id,
        }
      });
    }
    function iconHandle() {
      iconFlag.value = !iconFlag.value
    }


    // 1.处理逻辑
    const newCallback = () => { }
    const editCallback = () => {
    }

    const blackNewCallback = () => {
      console.log(blackInfo.value, 'blackNewCallback')
    }
    const blackEditCallback = () => {
      console.log(blackInfo.value, 'blackEditCallback')
    }

    // 2.动态添加部门和角色列表
    const modalConfigRef = computed(() => {

      const nativePlace = modalConfig.formItems.find(
        (item) => item.field === 'nativePlace'
      )
      if (nativePlace) nativePlace.options = areaTrees()

      const nation = modalConfig.formItems.find(
        (item) => item.field === 'nation'
      )
      if (nation) nation.options = nations

      const patientStatusConf = modalConfig.formItems.find(
        (item) => item.field === 'patientStatus'
      )
      if (patientStatusConf) patientStatusConf.options = patientStatus

      const sexConf = modalConfig.formItems.find(
        (item) => item.field === 'sex'
      )
      if (sexConf) sexConf.options = sex

      return modalConfig
    })

    const dialogFormVisible = ref(false);
    const changeType = ref(0);
    const dialogFormTitle = ref('');
    const batchLabels = async (type) => {

      const selectRows = pageContentRef.value.getSelectionRows()
      if (selectRows.length <= 0) {
        ElMessage({
          message: '请选择要操作的数据',
          type: 'warning',
        })

        return
      }
      changeType.value = type;
      dialogFormTitle.value = type ? '批量添加标签' : '批量取消标签'

      dialogFormVisible.value = true;
      selectTags.value = [];

      // ElMessageBox.prompt(boxTip, boxTitle, {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputPattern: /^[\w\u4E00-\u9FA5]{0,10}$/,
      //   inputErrorMessage: '只能输入中文、数字、字母 2-10个字符之间',
      // })
      //   .then(async ({ value }) => {
      //     // 获取选择的编号

      //     if (selectRows.length > 0) {
      //       const ids = selectRows.map((o) => o.patientId);

      //       let result;
      //       if (type === 1) {
      //         result = await setLabel(ids, value);
      //       } else {
      //         result = await cancelLabel(ids, value);
      //       }

      //       if (result.state === 'success') {
      //         ElMessage({
      //           message: '操作成功',
      //           type: 'success',
      //         })
      //         pageContentRef.value.getPageData()
      //       } else {
      //         // 失败
      //         ElMessage({
      //           message: '操作失败',
      //           type: 'error',
      //         })
      //       }
      //     }
      //   })
      //   .catch(() => {

      //   })
    }

    // 加入黑名单
    const blackOtherInfo = ref({
      patientId: '',
    });
    const joinBlacklist = async (row) => {
      blackOtherInfo.value.patientId = row.patientId;
      blackNewData();
    }

    const blackSubmit = (data) => {
      console.log('黑名单', data)
      // if (data.patientId) ElMessage.success('加入黑名单成功')
      // blackModalRef.value.dialogVisible = false
    }

    // const statusMap = ArrayToMap(patientStatus, 'value')

    // 3.调用hook获取公共变量和函数
    const [pageModalRef, defaultInfo, handleNewData, handleEditData] =
      usePageModal(newCallback, editCallback)

    const [blackModalRef, blackInfo, blackNewData, blackEditData] =
      usePageModal(blackNewCallback, blackEditCallback)

    const submit = () => {
      console.log('submit');
    }

    const selectTags = ref([]);

    const labels = ref([]);
    const labelCascaderRef = ref(null);
    const getLabelsTree = () => {
      getPageListData('/patient/tag/getdata').then(({ data }) => {
        labels.value = data;
      });
    }

    const batchChangeTag = async () => {
      const tags = selectTags.value;
      if (tags.length <= 0) {
        ElMessage({
          message: '请选择要标签',
          type: 'warning',
        })
        return
      }

      const selectRows = pageContentRef.value.getSelectionRows();

      console.log(tags, 'tags');
      if (selectRows.length > 0) {
        const ids = selectRows.map((o) => o.patientId);

        let result;
        if (changeType.value === 1) {
          result = await setLabel(ids, tags[tags.length - 1]);
        } else {
          result = await cancelLabel(ids, tags[tags.length - 1]);
        }

        if (result.state === 'success') {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          dialogFormVisible.value = false;
          pageContentRef.value.getPageData()
        } else {
          // 失败
          ElMessage({
            message: '操作失败',
            type: 'error',
          })
        }
      } else {
        ElMessage({
          message: '请选择要操作的数据',
          type: 'warning',
        })
      }

      
    }

    return {
      dialogFormTitle,
      batchChangeTag,
      selectTags,
      dialogFormVisible,
      labelCascaderRef,
      labels,
      submit,
      blackSubmit,
      userDecryptToAsterisk,
      blackOtherInfo,
      joinBlacklist,
      blackModalConfig: {
        subimitLoding: false,
        ...blackModalConfig,
      },
      blackInfo,
      blackModalRef,
      blackNewData,
      blackEditData,
      handleQueryClick,
      handleResetClick,
      batchLabels,
      statusMap: ArrayToMap(patientStatus, 'value'),
      sourceMap: ArrayToMap(patientSource, 'value'),
      sexMap: ArrayToMap(sex, 'value'),
      phoneStatusMap: ArrayToMap(phoneStatus, 'value'),
      buttonHandle,
      iconFlag,
      input2,
      activeNames,
      form,
      iconHandle,
      searchFormConfig,
      contentTableConfig,
      pageContentRef,
      modalConfigRef,
      pageModalRef,
      defaultInfo,
      handleNewData,
      handleEditData,
      userDecryptToAsterisk
    }
  }
})
</script>
<style lang="scss" scoped>
.page-search {
  width: 100%;
  position: relative;
  padding: 15px;

  .pos-icon {
    position: absolute;
    right: 15px;
    top: 20px;
    z-index: 11;
  }

  .search-header {
    .search-title {
      text-align: left;
      width: 100px;
      font-size: 18px;
      font-weight: bold;
    }

    .search-form {
      width: calc(100% - 100px);
      text-align: right;
    }
  }

  .serach-bottom {
    margin-top: 30px;
  }

  .btn-handle {}
}
</style>
