<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="96px">
      <el-form-item label="报工人" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入报工人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经办部门" prop="deptId">
        <el-select v-model="queryParams.deptId" filterable placeholder="请选择经办部门">
          <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报工时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          placeholder="请输入报工时间"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:projectReport:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:projectReport:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:projectReport:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:projectReport:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectReportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="经办人" align="center" prop="nickName">
        <template #default="scope">
          <span>{{ scope.row.nickName }}
          <template v-if="scope.row.deptName!=null">
            ({{ scope.row.deptName }})
          </template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="工作地点" align="center" prop="workPlace"/>
      <el-table-column label="国内/国外" align="center" prop="workType">
        <template #default="scope">
          <el-tag :type="scope.row.workType===0?'':'warning'">{{ scope.row.workType===0?'国内':'国外' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报工时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{parseTime(scope.row.createTime,'{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="View"
            @click="openDetail(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:projectReport:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oa:projectReport:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目报工对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">

        <el-form-item label="工作地点" prop="workPlace">
          <el-input v-model="form.workPlace" placeholder="请输入工作地点"/>
        </el-form-item>
        <el-form-item label="是否出差" prop="isTrip">
          <el-radio-group v-model="form.isTrip">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.isTrip===1">
          <el-form-item label="国内/国外" prop="workType">
            <el-radio-group v-model="form.workType">
              <el-radio :label="0">国内</el-radio>
              <el-radio :label="1">国外</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <el-form-item label="报工内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <!-- 只在编辑模式下显示报工时间 -->
        <el-form-item v-if="form.reportId" label="报工时间" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="请选择报工时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <project-report-detail
      v-model="detailVisible"
      :record="currentRow" />
  </div>
</template>

<script>
import {
  addProjectReport,
  delProjectReport,
  getProjectReport,
  listProjectReport,
  updateProjectReport
} from "@/api/oa/projectReport";
import { listDept } from "@/api/system/dept";
import ProjectReportDetail from "./components/ProjectReportDetail.vue";

export default {
  name: "ProjectReport",
  components: {ProjectReportDetail},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      detailVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目报工表格数据
      projectReportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        handler: undefined,
        workPlace: undefined,
        projectId: null,
        content: undefined,
      },
      deptList: [],
      currentRow:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workPlace: [
          {required: true, message: "工作地点不能为空", trigger: "blur"}
        ],
        content: [
          {required: true, message: "报工内容不能为空", trigger: "blur"}
        ],
        isTrip: [
          {required: true, message: '请选择是否出差', trigger: 'change'}
        ],
        workType: [
          {
            required: true, 
            message: '请选择出差地点', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.isTrip === 1 && !value && value !== 0) {
                callback(new Error('请选择出差地点'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询详情 */
    openDetail(row) {
      getProjectReport(row.reportId).then(response => {
        this.currentRow = response.data;   // row 为表格中选中的记录
        this.detailVisible = true;
      })

    },
    /** 自定义本地过滤：名称 | 编号 | 代码 任一匹配即可 */
    projectFilter(query) {
      // 1. 取出全部 option
      const options = this.$refs.projectSelect.options;

      // 2. 如果没输入，全部显示
      if (!query) {
        options.forEach(o => (o.visible = true));
        return;
      }

      const q = query.toLowerCase();

      // 3. 按三种字段匹配，决定每个 option 是否可见
      options.forEach(o => {
        // 根据 option.value 找到原始项目对象
        const item = this.projectList.find(p => p.projectId === o.value) || {};

        const hit = [item.projectName, item.projectNum, item.projectCode]
          .filter(Boolean)
          .some(text => text.toLowerCase().includes(q));

        o.visible = hit;
      });
    },

    getDeptList() {
      listDept().then(res => {
        this.deptList = res.data;
      })
    },
    /** 查询项目报工列表 */
    getList() {
      this.loading = true;
      listProjectReport(this.queryParams).then(response => {
        this.projectReportList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.getDeptList();
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reportId: undefined,
        handler: undefined,
        workPlace: undefined,
        projectId: undefined,
        content: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined,
        remark: undefined,
        isTrip: undefined,
        workType: undefined,
      };
      // 安全地重置表单，避免字段引用错误
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目报工";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const reportId = row.reportId || this.ids
      getProjectReport(reportId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目报工";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.reportId != null) {
            updateProjectReport({ ...this.form, time: this.form.createTime }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addProjectReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal.confirm('是否确认删除项目报工编号为"' + reportIds + '"的数据项？').then(() => {
        this.loading = true;
        return delProjectReport(reportIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/projectReport/export', {
        ...this.queryParams
      }, `projectReport_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
