<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单位名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" :value="true"></el-option>
          <el-option label="禁用" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="chargeCompanyList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="单位名称" prop="companyName" min-width="180"></el-table-column>
      <el-table-column label="联系人" prop="contactPerson" min-width="120"></el-table-column>
      <el-table-column label="联系电话" prop="contactPhone" min-width="150"></el-table-column>
      <el-table-column label="单位地址" prop="address" min-width="200"></el-table-column>
      <el-table-column label="状态" prop="status" min-width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            @change="handleStatusChange(scope.row)"
            :disabled="!checkPermi(['chargeCompany:status:edit'])"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" min-width="180"></el-table-column>
      <!-- <el-table-column label="创建时间" prop="createTime" min-width="180"></el-table-column> -->
      <el-table-column label="操作" min-width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改挂账单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <ChargeCompanyForm
        ref="chargeCompanyForm"
        v-model="formData"
        :systemCode="queryParams.systemCode || systemCode || ''"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChargeCompanyList, getChargeCompany, addChargeCompany, updateChargeCompany, deleteChargeCompany } from './api/chargeCompanyApi'
import Pagination from '@/components/Pagination'
import { getLastPathSegment } from '@/utils/ruoyi'
import ChargeCompanyForm from './form/ChargeCompanyForm'

export default {
  name: 'ChargeCompany',
  components: {
    Pagination,
    ChargeCompanyForm
  },
  props: {
    // 接收systemCode参数，默认为null，将在created钩子中初始化
    systemCode: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 挂账单位表格数据
      chargeCompanyList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        companyName: null,
        status: null,
        systemCode: ''
      },
      // 表单数据
      formData: {
        id: null,
        companyName: null,
        contactPerson: null,
        contactPhone: null,
        address: null,
        status: false,
        systemCode: '',
        remark: null
      }
    }
  },
  created() {
    // 设置systemCode，如果未传入则从路由中获取，并确保是字符串类型
    const currentSystemCode = String(this.systemCode || getLastPathSegment(this.$route.path))
    this.queryParams.systemCode = currentSystemCode
    this.formData.systemCode = currentSystemCode
    this.getList()
  },
  watch: {
    // 监听systemCode变化，确保传入字符串类型
    systemCode: function(newVal) {
      const systemCodeStr = String(newVal || '')
      this.queryParams.systemCode = systemCodeStr
      this.formData.systemCode = systemCodeStr
      this.getList()
    }
  },
  methods: {
    /** 查询挂账单位列表 */
    getList() {
      this.loading = true
      getChargeCompanyList(this.queryParams).then(response => {
        this.chargeCompanyList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 确保新增时带入systemCode
      this.formData.systemCode = this.queryParams.systemCode
      this.open = true
      this.title = '新增挂账单位'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getChargeCompany(id).then(response => {
        this.formData = response.data
        this.open = true
        this.title = '修改挂账单位'
      })
    },
    /** 状态变更 */
    handleStatusChange(row) {
      const statusMsg = row.status ? '启用' : '禁用'
      this.$modal.confirm(`是否确认${statusMsg}该挂账单位？`).then(() => {
        updateChargeCompany(row).then(() => {
          this.$modal.msgSuccess(`${statusMsg}成功`)
          this.getList()
        }).catch(() => {
          row.status = !row.status // 回滚状态
          this.$modal.msgError(`${statusMsg}失败`)
        })
      }).catch(() => {
        row.status = !row.status // 回滚状态
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.chargeCompanyForm.validate(valid => {
        if (valid) {
          if (this.formData.id != null) {
            updateChargeCompany(this.formData).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addChargeCompany(this.formData).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 重置表单 */
    reset() {
      this.formData = {
        id: null,
        companyName: null,
        contactPerson: null,
        contactPhone: null,
        address: null,
        status: false,
        systemCode: this.queryParams.systemCode,
        remark: null
      }
      if (this.$refs.chargeCompanyForm) {
        this.$refs.chargeCompanyForm.resetFields()
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除所选挂账单位？').then(() => {
        return deleteChargeCompany(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>