<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="部门名称">
          <el-input v-model="searchInfo.unitName" clearable placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门类型">
          <el-select v-model="searchInfo.remark" clearable placeholder="请选择">
            <el-option
              v-for="dict in dict.type.department_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="openDialog">新增部门</el-button>
          <!--          <el-button size="mini" type="primary" icon="el-icon-plus" @click="updateUnit">重新开始下期</el-button>-->
          <el-popover v-model:visible="deleteVisible" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="deleteVisible = false">取消</el-button>
              <el-button size="mini" type="primary" @click="onDelete">确定</el-button>
            </div>
            <!--            <template #reference>-->
            <!--              <el-button icon="el-icon-delete" size="mini" type="danger" style="margin-left: 10px;">批量删除</el-button>-->
            <!--            </template>-->
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="multipleTable"
      border
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="selection" width="55" />-->
      <!--      <el-table-column label="日期" width="180">-->
      <!--        <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>-->
      <!--      </el-table-column>-->
      <el-table-column label="部门名称" prop="unitName" />
      <el-table-column label="部门类型" prop="remark" />
      <el-table-column label="满分">
        <template #default="scope">{{ scope.row.unitMaxIntegral/100 }}</template>
      </el-table-column>
      <el-table-column label="扣分">
        <template #default="scope">{{ scope.row.unitIntegral/100 }}</template>
      </el-table-column>
      <el-table-column label="得分">
        <template #default="scope">{{ (scope.row.unitMaxIntegral-scope.row.unitIntegral)/100 }}</template>
      </el-table-column>
      <el-table-column label="得分率">
        <template #default="scope">{{ ((scope.row.unitMaxIntegral-scope.row.unitIntegral)/scope.row.unitMaxIntegral).toFixed(4)*100?((scope.row.unitMaxIntegral-scope.row.unitIntegral)/scope.row.unitMaxIntegral).toFixed(4)*100:0 }} %</template>
      </el-table-column>
      <el-table-column label="按钮组">
        <template #default="scope">
          <el-button size="small" type="primary" icon="el-icon-edit" class="table-button" @click="updateUnit(scope.row)">变更</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>
          <el-button size="small" type="primary" icon="el-icon-edit" @click="selecrUser(scope.row)">负责人管理</el-button>
          <el-button size="small" type="primary" icon="el-icon-edit" @click="selectPlace(scope.row)">添加考察点位</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <el-dialog v-model="noticeList" title="选择负责人" width="500px" append-to-body>
      <el-form v-model="bindUser" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门负责人" :rules="{required: true, message: '请选择部门负责人'}">
              <el-select
                v-model="bindUser.userList"
                filterable
                clearable
                multiple
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="id in Object.keys(userIds)"
                  :key="id"
                  :label="userIds[id]"
                  :value="id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUser">确 定</el-button>
        <el-button @click="closeSend">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="弹窗操作">
      <el-form :model="formData" label-position="right" label-width="80px">
        <el-form-item label="部门名称:">
          <el-input v-model="formData.unitName" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="部门类型:">
          <el-select v-model="formData.remark" clearable placeholder="请选择">
            <el-option
              v-for="dict in dict.type.department_type"
              :key="dict.label"
              :label="dict.label"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="placesVisible" :before-close="closePlace" title="管理部门点位">
      <el-form :model="placesForm" label-position="right" label-width="80px">
        <el-form-item label="评分站点:">
          <el-select
            v-model="placesForm.placesId"
            filterable
            clearable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="id in Object.keys(places)"
              :key="id"
              :label="places[id]"
              :value="id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closePlace">取 消</el-button>
          <el-button type="primary" @click="enterDialogPlace">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisiblePro" :before-close="closeDialogPro" title="扣分详情">
      <div>
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pagePro"
          :page-size="pageSizePro"
          :page-sizes="[10, 30, 50, 100]"
          :style="{float:'right',padding:'20px'}"
          :total="totalPro"
          @current-change="handleCurrentChangePro"
          @size-change="handleSizeChangePro"
        />
        <el-table
          ref="crudItem"
          border
          stripe
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableDataPro"
        >
          <el-table-column label="日期" width="180">
            <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
          </el-table-column>
          <el-table-column label="发布人" prop="oper" />
          <el-table-column label="站点" prop="siteName" />
          <el-table-column label="站点类型" prop="siteType">
            <template #default="scope">
              <dict-tag :options="dict.type.site_type" :value="scope.row.siteType" />
            </template>
          </el-table-column>
          <el-table-column label="已登录查阅次数" prop="count" />
          <el-table-column label="一类部门" prop="unitName" />
          <el-table-column label="扣评分" prop="integral">
            <template #default="scope">{{ scope.row.integral/100 }}</template>
          </el-table-column>
          <el-table-column label="处理状态" prop="status">
            <template #default="scope">
              <el-tag v-show="scope.row.status == 'Untreated'" type="warning">未处理</el-tag>
              <el-tag v-show="scope.row.status == 'Processed'" type="success">已处理</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="责任部门" prop="department" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createUnit,
  deleteUnit,
  deleteUnitByIds,
  updateUnit,
  getUnitList, findUnit
} from '@/api/unit' //  此处请自行替换地址
import infoList from '@/mixins/infoList'
import { getProblemInfoList } from '@/api/problemInfo'
import { getUserPList } from '@/api/user'
import { updateUnitUser, getUnitUserList } from '@/api/unitUser'
import { getPlaceList } from '@/api/place'
import { getUnitPlaceList, updateUnitPlace } from '@/api/unitPlace'
export default {
  name: 'Unit',
  dicts: ['department_type'],
  mixins: [infoList],
  data() {
    return {
      listApi: getUnitList,
      listProApi: getProblemInfoList,
      dialogFormVisible: false,
      noticeList: false,
      userIds: {},
      placesVisible: false,
      places: {},
      placesForm: {
        placesId: [],
        unitId: '',
      },
      type: '',
      deleteVisible: false,
      multipleSelection: [],
      dialogFormVisiblePro: false,
      tableDataPro: [],
      pagePro: 1,
      totalPro: 10,
      pageSizePro: 10,
      bindUser: {
      },
      searchInfoPro: {
        CreatedAtStart: new Date(),
        CreatedAtEnd: new Date()
      },
      formData: {
        unitName: '',
        unitIntegral: 100,
      }
    }
  },
  async created() {
    await this.getTableData()
    getPlaceList({ page: 1, pageSize: 9999 }).then(res => {
      for (const place in res.data.list) {
        this.places[res.data.list[place].ID] = res.data.list[place].name
      }
    })
  },
  methods: {
  // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteRow(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUnit(row)
      })
    },
    async onDelete() {
      const ids = []
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      this.multipleSelection &&
        this.multipleSelection.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteUnitByIds({ ids })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    selectPlace(row) {
      this.unitId = row.ID
      getUnitPlaceList({ unitId: this.unitId }).then(res => {
        this.placesForm.placesId = res.data.list.map(item => item.placeId)
        this.placesVisible = true
      })
    },
    enterDialogPlace() {
      updateUnitPlace({ unitId: this.unitId, placeIds: this.placesForm.placesId }).then(res => {
        this.closePlace()
      })
    },
    closePlace() {
      this.placesForm = { placesId: [],
        unitId: '' }
      this.unitId = ''
      this.placesVisible = false
    },
    async selecrUser(row) {
      this.unitId = row.ID
      this.noticeList = true
      getUnitUserList({ unitId: this.unitId }).then(res => {
        this.bindUser.userList = res.data
      })
      getUserPList({ page: 1, pageSize: 9999 }).then(res => {
        for (const user in res.data.list) {
          this.userIds[res.data.list[user].uuid] = res.data.list[user].userName
        }
      })
    },
    closeSend() {
      this.noticeList = false
      this.userIds = {}
      this.bindUser.userList = []
      this.unitId = ''
    },
    saveUser() {
      updateUnitUser({ unitId: this.unitId, uuid: this.bindUser.userList }).then(res => {
        this.closeSend()
      })
    },
    async updateUnit(row) {
      const res = await findUnit({ ID: row.ID })
      this.formData = res.data.reunit
      this.type = 'update'
      this.dialogFormVisible = true
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.formData = {
        unitName: '',
        unitIntegral: 100,
      }
    },
    async deleteUnit(row) {
      const res = await deleteUnit({ ID: row.ID })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      let res
      switch (this.type) {
        case 'create':
          res = await createUnit(this.formData)
          break
        case 'update':
          res = await updateUnit(this.formData)
          break
        default:
          res = await createUnit(this.formData)
          break
      }
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '创建/更改成功'
        })
        this.closeDialog()
        this.getTableData()
      }
    },
    openDialog() {
      this.type = 'create'
      this.dialogFormVisible = true
    },
    openProDialog(row) {
      this.dialogFormVisiblePro = true
      const formatDateStr = row.period.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1/$2/$3 $4:$5:$6')
      // 将时间格式化成 yyyy-MM-dd HH:mm:ss
      this.searchInfoPro.CreatedAtStart = new Date(formatDateStr)
      this.searchInfoPro.CreatedAtEnd = new Date()
      this.searchInfoPro.unitId = row.ID
      this.getTableDataPro()
    },
    handleSizeChangePro(val) {
      this.pageSizePro = val
      this.getTableDataPro()
    },
    handleCurrentChangePro(val) {
      this.pagePro = val
      this.getTableDataPro()
    },
    closeDialogPro() {
      this.dialogFormVisiblePro = false
      this.formData = {
        unitName: '',
        unitIntegral: 0,
      }
    },
    getTableDataPro(page = this.pagePro, pageSize = this.pageSizePro) {
      this.listProApi({ page, pageSize, ...this.searchInfoPro }).then(res => {
        console.log(res)
        if (res.code === 0) {
          this.tableDataPro = res.data.list
          this.totalPro = res.data.total
          this.pagePro = res.data.page
          this.pageSizePro = res.data.pageSize
        }
      })
    }
  },
}
</script>

<style>
</style>
