<script setup>
import { useRouter, useRoute } from 'vue-router';
import { servicesApi } from '@/api/voice/services';
import { noticeApi } from '@/api/voice/notice';
import { ElMessage } from 'element-plus'
import BaseLayoutViewport from '@/components/BaseLayout';

const router = useRouter();
const route = useRoute();

const formRef = ref(null);
const pumpingValue = ref(null);
const housingValue = ref(null);
const pumpingOptions = ref([]);
const housingOptions = ref([]);

const formData = ref({
  timeBegin: '',
  timeEnd: '',
  reason: ''
})

const tableData = ref([]);

const rules = reactive({
  timeBegin: [
    { required: true, message: '请选择停水时间', trigger: 'blur' },
  ],
  reason: [
    { required: true, message: '请输入停水原因', trigger: 'blur' },
  ]
});

// 删除
const handleDelRow = (row) => {
  tableData.value.splice(row.$index, 1);
}

// 添加泵站
const addTableData = async (type) => {
  if ( type == 0 && !pumpingValue.value) {
    return ElMessage.warning("请先选择泵站");
  }
  if ( type == 1 && !housingValue.value) {
    return ElMessage.warning("请先选择小区");
  }
  const { data } = await noticeApi.getExtraListByType({ type, id: type == 0 ? pumpingValue.value : housingValue.value })
  
  const combined = tableData.value.concat(data);

  const unique = Array.from(new Map(combined.map(item => [JSON.stringify([item.neighbourhoodId, item.pumpingStationId]), item])).values());

  tableData.value = unique;
}

// 最终提交
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if ( !tableData.value.length ) {
        return ElMessage.warning("请先选择停水范围");
      }
      const id = route.query.id;
      if (id) {
        await noticeApi.putWater({...formData.value, extraResList: tableData.value}).then(() => {
          ElMessage.success("停水公告修改成功");
        })
      } else {
        await noticeApi.postWater({...formData.value, extraResList: tableData.value}).then(() => {
          ElMessage.success("停水公告添加成功");
        })
      }
      goBack();
    }
  })
}

const goBack = () => {
  router.push('/voice/notice')
}

const onCleanTableData = () => {
  tableData.value = [];
  pumpingValue.value = [];
  housingValue.value = [];
}

onMounted(() => {
  const id = route.query.id;
  if ( id ) {
    noticeApi.getWater(id).then(({ data }) => {
      const { timeBegin, timeEnd, reason, extraResList } = data;
      formData.value = {
        timeBegin,
        timeEnd,
        reason,
        id
      }
      tableData.value = extraResList;
    })
  }

  // 泵站
  servicesApi.getPumpingList({pageSize: 10000, pageNum: 1}).then(res => {
    pumpingOptions.value = res.data;
  })
  // 小区
  servicesApi.getNeighborhoodList({pageSize: 10000, pageNum: 1}).then(res => {
    housingOptions.value = res.rows;
  })
})


</script>

<template>
  <BaseLayoutViewport title="添加停水公告">
    <div class="px-[20px]">
      <div class="reply-tips-card space-x-[4px]">
        <img src="@/assets/images/notice/icon-tips.svg" alt="">
        <ul class="tips-content space-y-[8px]">
          <li>语音回复话术：</li>
          <li>
            <span>#停水原因#</span>,于<span>#停水时间#</span>进行停水处理，预计<span>#供水恢复时间#</span> 恢复供水。如遇到其他情况无法按时恢复供水，请关注****公众号获取最新恢复供水时间
            <br>或再次拨打190热线进行咨询。
          </li>
        </ul>
      </div>
  
      <div class="pt-[20px]">
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="auto" label-position="left">
          <el-row :gutter="20" style="width: 900px;">
            <el-col :span="24" style="display: flex; align-items: flex-start; justify-content: space-between;">
              <el-form-item label="停水时间" prop="timeBegin">
                <div>
                  <el-date-picker
                    v-model="formData.timeBegin"
                    type="datetime"
                    placeholder="请选择停水时间"
                    style="width: 280px;"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </div>
              </el-form-item>
              <el-form-item label="恢复供水时间" prop="timeEnd">
                <div>
                  <el-date-picker
                    v-model="formData.timeEnd"
                    type="datetime"
                    placeholder="请选择恢复供水时间"
                    style="width: 280px;"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                  <p class="h-[22px] text-[12px] text-[#999]">如无法确定恢复供水时间， 则不填写</p>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="停水原因" prop="reason">
                <el-input v-model="formData.reason" placeholder="请输入停水原因" type="textarea" :autosize="{ minRows: 8, maxRows: 6 }" resize="none"/>
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <el-form-item label="停水范围" required style="width: 100%;">
              <div class="flex justify-between">
                <ul class="select-group space-x-[40px] mr-[20px]" style="width: 784px;">
                  <li class="space-x-[5px]">
                    <span>根据泵站添加：</span>
                      <!-- multiple
                      collapse-tags
                      collapse-tags-tooltip
                      :max-collapse-tags="1" -->
                    <el-select
                      v-model="pumpingValue"
                      placeholder="请选择"
                      filterable
                      style="width: 200px;"
                    >
                      <el-option
                        v-for="item in pumpingOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                    <div class="custom-btn custom-btn_primary" @click="addTableData(0)">添加</div>
                  </li>
                  <li class="space-x-[5px]">
                    <span>根据小区添加：</span>
                    <el-select
                      v-model="housingValue"
                      placeholder="请选择"
                      filterable
                      style="width: 200px;"
                    >
                      <el-option
                        v-for="item in housingOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                    <div class="custom-btn custom-btn_primary" @click="addTableData(1)">添加</div>
                  </li>
                </ul>
                <div class="custom-btn custom-btn_primary" @click="onCleanTableData">重置</div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
  
      <div class="table-card">
        <el-table :data="tableData" style="width: 100%" >
          <el-table-column prop="pumpingStationName" label="所属泵站" align="center" />
          <el-table-column prop="neighbourhoodName" label="小区名称" align="center"></el-table-column>
          <el-table-column prop="neighbourhoodNumberNames" label="楼号" align="center" />
          <el-table-column prop="neighbourhoodAddress" label="详细地址" align="center" />
          <el-table-column prop="address" label="操作" align="center" width="150">
            <template #default="scope">
              <span class="text-[#165DFF] cursor-pointer" @click="handleDelRow(scope)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <ul class="flex justify-center space-x-[12px]">
        <li class="custom-btn custom-btn_primary" @click="submitForm">保存</li>
        <li class="custom-btn custom-btn_default" @click="goBack">返回</li>
      </ul>
    </template>
  </BaseLayoutViewport>
</template>

<style lang="scss" scoped>
.title {
  margin-bottom: 24px;
  color: #1D2129;
  font-size: 18px;
  font-weight: bold;
  line-height: 26px;
}

:deep(.el-date-editor) {
  .el-input__wrapper {
    height: 36px;
  }
  &.el-input {
    height: 36px;
  }
}

.reply-tips-card {
  display: flex;
  align-items: start;
  height: 100px;
  padding: 14px 0 0 16px;
  border-radius: 8px;
  background: #E6EEFF;
  overflow: hidden;

  img {
    width: 24px;
    height: 24px;
    flex-shrink: 0;
  }

  .tips-content {
    li:nth-child(1) {
      font-weight: bold;
      font-size: 16px;
      line-height: 24px;
    }
    li:nth-child(2) {
      font-size: 14px;
      line-height: 22px;
      white-space:nowrap;
      span {
        color: #165DFF;
      }
    }
  }
}

.select-group {
  display: flex;
  justify-content: space-between;
  width: 100%;
  li {
    display: flex;
    span {
      font-size: 14px;
      white-space: nowrap;
      color: #86909C;
    }

    // reset select
    :deep(.el-select__wrapper) {
      height: 100%;
      min-height: auto;
    }

    // reset date-picker
    :deep(.el-input__icon ) {
      display: none;
    }
  }
}
</style>