<template>
  <el-dialog
    :model-value="props.modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="安全责任通知发送"
    width="800"
    @close="clearData"
  >
    <el-tabs v-model="activeTab">
      <el-tab-pane :disabled="activeTab !== 1" label="公共区域" :name="1" />
      <el-tab-pane :disabled="activeTab !== 2" label="非公共区域" :name="2" />
    </el-tabs>
    <div class="main">
      <el-form ref="formRef" :rules="rules" :model="formValue">
        <el-form-item label="计划开始日期" prop="planStartTime">
          <el-date-picker v-model="formValue.planStartTime" placeholder="请选择日期" style="width: 200px" />
        </el-form-item>

        <el-form-item label="计划结束日期" prop="planEndTime">
          <el-date-picker v-model="formValue.planEndTime" placeholder="请选择日期" style="width: 200px" />
        </el-form-item>
        <el-form-item label="通知区域" prop="safetyAreaData">
          <el-button @click="handleAddArea" type="primary" :icon="Plus">添加</el-button>
        </el-form-item>
        <el-table :data="currentTableData" v-if="formValue.safetyAreaData.length" style="width: 100%; margin: 20px 0 0">
          <!-- <el-table-column type="index" label="序号" width="80" /> -->
          <el-table-column label="楼宇/区域" v-if="formValue.type === 1" prop="buildingArea" width="180" />
          <el-table-column label="楼层/房号" v-if="formValue.type === 1" prop="floorRoomNo" width="180" />
          <el-table-column label="名称/功能" v-if="formValue.type === 1" prop="nameFunction" width="120" />

          <el-table-column v-if="formValue.type === 2" label="楼号" prop="buildingNo" width="100" />
          <el-table-column v-if="formValue.type === 2" label="楼层" prop="buildingArea" width="100" />
          <el-table-column v-if="formValue.type === 2" label="房间/区域" prop="floorRoomNo" width="180" />
          <el-table-column v-if="formValue.type === 2" label="功能名称" prop="nameFunction" width="120" />

          <el-table-column label="安全责任所/中心" prop="safetyResponsibleCenter" width="200" />
          <el-table-column label="安全责任所/中心负责人" prop="safetyCenterManagerName" width="200" />
          <el-table-column label="安全责任部门" prop="safetyResponsibleDepartment" width="180" />
          <el-table-column label="安全责任部门负责人" prop="safetyDepartmentManagerName" width="180" />
          <el-table-column label="安全具体责任人" prop="safetySpecificPersonName" width="180" />
          <el-table-column label="安全具体责任人联系方式" prop="safetyPersonContact" width="230" />
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleDeleteArea(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="formValue.safetyAreaData.length">
          <el-pagination
            background
            :current-page="queryParams.pageNumber"
            :page-size="queryParams.pageSize"
            :total="formValue.safetyAreaData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-form>
    </div>
    <SelectNotifyArea
      v-if="selectNotifyAreaOpen"
      v-model.visible="selectNotifyAreaOpen"
      :type="activeTab"
      :append-to-body="true"
      @submit="handleSelectionTableData"
    />

    <template #footer>
      <div>
        <el-button type="primary" @click="submitForm" :loading="submitLoading"> 确定 </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElButton } from 'element-plus';
  import SelectNotifyArea from './SelectNotifyArea.vue';
  import { uniqBy, omit } from 'lodash-es';
  import dayjs from 'dayjs';
  import { safetyNoticeAdminIssuedNotice } from '@/api/production-safety/responsibility-implementation';
  import { Plus } from '@element-plus/icons-vue';

  const props = defineProps<{
    type: number;
    modelValue: boolean;
  }>();

  const formRef = ref<any>(null);
  const emit = defineEmits(['close', 'submit', 'update:modelValue']);
  const submitLoading = ref(false);
  const activeTab = ref(props.type);
  const selectionList = ref([]);
  const selectNotifyAreaOpen = ref(false);
  const currentTableData = ref([]);

  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 3,
    // queryParam: {
    //   type: activeTab.value,
    //   planStartTime: null,
    //   planEndTime: null,
    // },
  });
  const formValue = reactive({
    type: props.type,
    safetyAreaData: [], // 区域分组,多个用，分隔
    planStartTime: null, // 计划开始日期
    planEndTime: null, // 计划结束日期
  });

  const tableData = reactive<any>({
    data: [],
    total: 0,
  });

  const rules = reactive({
    planStartTime: [
      {
        required: true,
        message: '请选择计划开始时间',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value && formValue.planEndTime) {
            if (dayjs(value).isAfter(formValue.planEndTime)) {
              callback(new Error('开始日期不能大于结束日期'));
              return;
            }
          }
          callback();
        },
      },
    ],
    planEndTime: [
      {
        required: true,
        message: '请选择计划结束时间',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value && formValue.planStartTime) {
            if (dayjs(value).isBefore(formValue.planStartTime)) {
              callback(new Error('结束日期不能小于开始日期'));
              return;
            }
          }
          callback();
        },
      },
    ],
    safetyAreaData: [
      {
        required: true,
        message: '请选择区域',
        trigger: 'change',
      },
      {
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            callback(new Error('区域不能为空'));
          }
          callback();
        },
      },
    ],
  });

  function dialogShow() {}
  function dialogHide() {
    emit('close');
  }
  function clearData() {}

  function submitForm() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return;
      }
      emit('submit', formValue, submitLoading);
      // emit('update:modelValue', false);
    });
  }

  const handleDeleteArea = (scope) => {
    formValue.safetyAreaData = formValue.safetyAreaData.filter((item: any) => item.id !== scope.row.id);
    const totalPages = Math.ceil(formValue.safetyAreaData.length / queryParams.pageSize);
    if (queryParams.pageNumber > totalPages) {
      queryParams.pageNumber = totalPages || 1;
    }
    displayData(queryParams.pageNumber);
  };
  const displayData = (page = 1) => {
    const start = (page - 1) * queryParams.pageSize;
    const end = start + queryParams.pageSize;
    currentTableData.value = formValue.safetyAreaData.slice(start, end);
  };
  const handleCurrentChange = (page: number) => {
    queryParams.pageNumber = page;
    displayData(page);
  };

  const handleSizeChange = (size: number) => {
    queryParams.pageSize = size;
  };

  const handleSelectionTableData = (data) => {
    tableData.total = data.length;
    tableData.data = [...tableData.data, ...data];
    Object.assign(formValue, {
      safetyAreaData: uniqBy(tableData.data, 'id'),
    });
    formRef.value?.validateField('safetyAreaData');
    displayData();
  };
  const handleAddArea = () => {
    selectNotifyAreaOpen.value = true;
  };

  const handleCloseAreaDialog = () => {
    selectNotifyAreaOpen.value = false;
  };

  const handleCancel = () => {
    selectionList.value = [];
    emit('update:modelValue', false);
  };

  watch(
    () => props.type,
    (a, b) => {
      activeTab.value = a;
    },
  );

  defineExpose({
    submitLoading,
    dialogShow,
    dialogHide,
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;

  .main {
    display: flex;
    flex-direction: column;
    max-height: 400px;
  }

  .table-content {
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
  }

  .pagination-container {
    margin-top: 20px;
  }
</style>
