<template>
  <div class="divBox">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="业主类型">
        <el-select v-model="dataForm.ownerType" placeholder="请选择业主类型" clearable>
          <el-option
            v-for="dict in dict.type.owner_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报修单号">
        <el-input v-model="dataForm.orderNo" placeholder="请输入报修单号" clearable></el-input>
      </el-form-item>
      <el-form-item label="故障类型">
        <el-select v-model="dataForm.faultType" placeholder="请选择故障类型" clearable>
          <el-option
            v-for="dict in dict.type.fault_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="dataForm.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.fault_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
        <el-button v-hasPermi="['autogencode:pmmaintenanceorder:save']" type="primary" @click="addOrUpdateHandle()">新增报修</el-button>
        <el-button v-hasPermi="['autogencode:pmmaintenanceorder:delete']" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      @expand-change="handleExpandChange"
      :expand-row-keys="expandedRowKeys"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column type="expand" header-align="center" align="center">
        <template slot-scope="scope">
          <DispatchList
            :orderId="scope.row.id"
            @addDispatch="addDispatch"
            @editDispatch="editDispatch"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="ownerType"
        header-align="center"
        align="center"
        label="业主类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.owner_type" :value="scope.row.ownerType"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="ownerName"
        header-align="center"
        align="center"
        label="业主/租户">
      </el-table-column>
      <el-table-column
        prop="houseName"
        header-align="center"
        align="center"
        label="房屋名称">
      </el-table-column>
      <el-table-column
        prop="orderNo"
        header-align="center"
        align="center"
        label="报修单号">
      </el-table-column>
      <el-table-column
        prop="faultType"
        header-align="center"
        align="center"
        label="故障类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fault_type" :value="scope.row.faultType"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="faultDesc"
        header-align="center"
        align="center"
        show-overflow-tooltip
        label="故障描述">
      </el-table-column>
      <el-table-column
        prop="reportChannel"
        header-align="center"
        align="center"
        label="报修渠道">
      </el-table-column>
      <el-table-column
        prop="reportTime"
        header-align="center"
        align="center"
        label="报修时间">
      </el-table-column>
      <el-table-column
        prop="urgencyLevel"
        header-align="center"
        align="center"
        label="紧急程度">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fault_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        show-overflow-tooltip
        label="备注">
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ '修改' }}</el-button>
          <el-button v-if="scope.row.status !== '99'" type="text" size="small" @click="completeOrder(scope.row.id)">{{ '办结' }}</el-button>
          <el-button v-hasPermi="['autogencode:pmmaintenanceorder:delete']" type="text" size="small" @click="deleteHandle(scope.row.id)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 表单弹窗, 新增数据和修改数据 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

  </div>
</template>

<script>
  import AddOrUpdate from './pmmaintenanceorder-add-and-update'
import DispatchList from './DispatchList'
import * as api from '@/api/pmmaintenanceorder.js'
import * as ownerApi from '@/api/pmowner.js'
import * as houseApi from '@/api/pmhouse.js'
import DictTag from '@/components/DictTag'
  export default {
    dicts: ['owner_type','fault_type','fault_status'],
    data () {
      return {
        dataForm: {
          ownerType: '',
          ownerId: '',
          houseId: '',
          houseOwnerId: '',
          orderNo: '',
          faultType: '',
          faultDesc: '',
          faultPhoto: '',
          reportChannel: '',
          reportTime: '',
          urgencyLevel: '',
          status: '',
          remark: '',
        },

        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        ownerList: [],
        houseList: [],
        expandedRowKeys: [] // 存储展开的行的ID
      }
    },
    components: {
      AddOrUpdate,
      DispatchList,
      DictTag
    },
    activated () {
      this.getDataList()
    },
    mounted() {
      this.getDataList()
      // 加载业主、房屋和派单记录列表
      this.loadOwnerList()
      this.loadHouseList()
    },
    methods: {
      // 加载业主列表
      loadOwnerList() {
        ownerApi.pmownerListApi({ page: 1, limit: 9999 }).then(res => {
          this.ownerList = res.list || []
        })
      },
      // 加载房屋列表
      loadHouseList() {
        houseApi.pmhouseListApi({ page: 1, limit: 9999 }).then(res => {
          this.houseList = res.list || []
        })
      },
      // 处理行的展开和折叠事件
      handleExpandChange(row, expandedRows) {
        if (expandedRows.includes(row)) {
          // 展开行，将其ID添加到 expandedRowKeys 数组
          if (!this.expandedRowKeys.includes(row.id)) {
            this.expandedRowKeys.push(row.id)
          }
        } else {
          // 折叠行，将其ID从 expandedRowKeys 数组中移除
          const index = this.expandedRowKeys.indexOf(row.id)
          if (index !== -1) {
            this.expandedRowKeys.splice(index, 1)
          }
        }
      },


      // 重置表单
      resetForm() {
        this.dataForm = {
          ownerType: '',
          ownerId: '',
          houseId: '',
          houseOwnerId: '',
          orderNo: '',
          faultType: '',
          faultDesc: '',
          faultPhoto: '',
          reportChannel: '',
          reportTime: '',
          urgencyLevel: '',
          status: '',
          remark: '',
        }
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        // 根据后端PmMaintenanceOrderController和PageParamRequest的期望格式构建参数
        const params = {
          page: this.pageIndex,
          limit: this.pageSize
        }

        // 将查询条件添加到参数中
        if (this.dataForm.ownerType) params.ownerType = this.dataForm.ownerType;
        if (this.dataForm.ownerId) params.ownerId = this.dataForm.ownerId;
        if (this.dataForm.houseId) params.houseId = this.dataForm.houseId;
        if (this.dataForm.houseOwnerId) params.houseOwnerId = this.dataForm.houseOwnerId;
        if (this.dataForm.orderNo) params.orderNo = this.dataForm.orderNo;
        if (this.dataForm.faultType) params.faultType = this.dataForm.faultType;
        if (this.dataForm.faultDesc) params.faultDesc = this.dataForm.faultDesc;
        if (this.dataForm.faultPhoto) params.faultPhoto = this.dataForm.faultPhoto;
        if (this.dataForm.reportChannel) params.reportChannel = this.dataForm.reportChannel;
        if (this.dataForm.reportTime) params.reportTime = this.dataForm.reportTime;
        if (this.dataForm.urgencyLevel) params.urgencyLevel = this.dataForm.urgencyLevel;
        if (this.dataForm.status) params.status = this.dataForm.status;
        if (this.dataForm.remark) params.remark = this.dataForm.remark;

        api.pmmaintenanceorderListApi(params).then(res => {
          this.dataListLoading = false
          this.dataList = res.list || [];
          this.totalPage = res.total;
        }).catch(e => {
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除处理（支持单个删除和批量删除）
      deleteHandle (id) {
        let ids = []
        let idText = ''

        // 如果传入了单个id参数，则为单个删除
        if (id) {
          ids = [id]
          idText = id
        } else {
          // 否则为批量删除
          ids = this.dataListSelections.map(item => {
            return item.id
          })
          idText = ids.join(',')
        }

        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用批量删除API
          api.pmmaintenanceorderDeleteApi(ids).then(res => {
            this.$message.success('删除成功')
            this.getDataList()
          })
        })
      },
      // 办结订单
      completeOrder (id) {
        this.$prompt('请输入办结备注', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入备注信息'
        }).then(({ value }) => {
          // 调用更新状态和备注的API
          api.pmmaintenanceorderUpdateStatusAndRemarkApi({
            id: id,
            status: '99', // 99是已办结状态
            remark: value
          }).then(res => {
            this.$message.success('办结成功')
            this.getDataList()
          }).catch(() => {
            this.$message.error('办结失败')
          })
        }).catch(() => {
          this.$message.info('已取消办结')
        })
      },
    }
  }
</script>
