<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司" prop="comId" v-if="1 == 2">
        <el-input v-model="queryParams.comId" placeholder="请输入公司主键" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select :disabled="data.currentProId != ''" v-model="queryParams.projectId" placeholder="请选择项目" clearable
          @change="handleQuery">
          <el-option v-for="prj in data.projects" :key="prj.id" :label="prj.projectName" :value="prj.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考勤厂商" prop="vendorsCode">
        <el-select v-model="queryParams.vendorsCode" placeholder="请选择厂商" clearable @change="handleQuery">
          <el-option v-for="dict in attendance_vendors" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="启停状态" prop="enabled">
        <el-select v-model="queryParams.enabled" clearable style="width:100px;">
          <el-option label="启用" :value="1"></el-option>
          <el-option label="停用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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" @click="handleAdd"
          v-hasPermi="['manage:attendance_cfg:add']">新增</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:attendance_cfg:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:attendance_cfg:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:attendance_cfg:export']">导出</el-button>
      </el-col>
      -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendance_cfgList" @selection-change="handleSelectionChange">
      <el-table-column label="NO." align="center" prop="id" />
      <el-table-column label="所属公司" align="center" prop="compName" />
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="考勤厂商" align="center" prop="vendorsName">
        <template #default="scope">
        <span style="color: var(--el-color-warning);">{{scope.row.vendorsName }}</span>
      </template>
      </el-table-column>
      <el-table-column label="实名制项目ID" align="center" prop="info.projectGuid" />
      <el-table-column label="应用KEY" align="center" prop="info.AppKey" />
      <el-table-column label="应用Secret" align="center" prop="info.AppSecret" />
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template #default="scope">
          <el-switch v-model="scope.row.enabled" :active-value="1" @change="doUpdateRow(scope.row)" :inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="添加用户" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template #default="scope">
          <el-button link type="primary" icon="Football" @click="handleDeviceList(scope.row)"
            v-hasPermi="['manage:attendance_cfg:edit']">设备列表</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:attendance_cfg:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:attendance_cfg:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改考勤配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="attendance_cfgRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属项目" prop="projectId">
          <el-select :disabled="data.currentProId != ''||data.mode=='edit'" v-model="form.projectId" placeholder="请选择项目">
            <el-option v-for="prj in data.projects" :key="prj.id" :label="prj.projectName" :value="prj.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考勤厂商" prop="vendorsCode">
          <el-select v-model="form.vendorsCode" placeholder="请选择厂商">
            <el-option v-for="dict in attendance_vendors" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.vendorsCode == 'uni'">
          <el-form-item label="应用KEY" prop="AppKey">
            <el-input v-model="form.AppKey" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="应用Secret" prop="AppSecret">
            <el-input v-model="form.AppSecret" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="项目ID" prop="projectGuid">
            <el-input v-model="form.projectGuid" placeholder="请输入内容" />
          </el-form-item>
        </template>

        <el-form-item label="已启用" prop="enabled">
          <el-switch v-model="form.enabled" :active-value="1" :inactive-value="0"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <ubiDeviceDrawer ref="deviceDrawer"></ubiDeviceDrawer>
  </div>
</template>

<script setup name="Attendance_cfg">
import { listAttendance_cfg, getAttendance_cfg, delAttendance_cfg, addAttendance_cfg, updateAttendance_cfg } from "@/api/manage/attendanceCfg";
import { findMyProjectList } from "@/api/publics";
import useUserStore from '@/store/modules/user'
import ubiDeviceDrawer from '../attendance_ubi_device/ubiDeviceDrawer.vue'
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const { attendance_vendors } = proxy.useDict('attendance_vendors');


const attendance_cfgList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deviceDrawer=ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    comId: null,
    projectId: null,
    vendorsCode: null,
    vendorsParameter: null,
    enabled: null,
    state: null,
    isDel: null,
  },
  rules: {
    projectId: [{ required: true, trigger: ['blur', 'change'], message: "请选择所属项目" }],
    vendorsCode: [{ required: true, trigger: ['blur', 'change'], message: "请选择考勤厂商" }],
    AppKey: [{ required: true, trigger: ['blur', 'change'], message: "请输入应用KEY" }],
    AppSecret: [{ required: true, trigger: ['blur', 'change'], message: "请输入应用Secret" }],
    projectGuid: [{ required: true, trigger: ['blur', 'change'], message: "请输入项目Guid" }],
  },
  projects: [],
  currentProId: '',
  mode:'',
});

const { queryParams, form, rules } = toRefs(data);

function doUpdateRow(row){
  updateAttendance_cfg(row).then(d=>{
    proxy.$modal.msgSuccess("修改成功");
  });
}

/**设备列表 */
function handleDeviceList(row){
  deviceDrawer.value.showDrawer(row);
}
/** 查询项目列表 */
function getProjectList() {
  findMyProjectList({ pageNum: 1, pageSize: 100 }).then(response => {
    data.projects = response.rows;
    if (userStore.currentProId) {
      queryParams.value.projectId = userStore.currentProId
      data.currentProId = userStore.currentProId;
    }
  });
}

/** 查询考勤配置列表 */
function getList() {
  loading.value = true;
  listAttendance_cfg(queryParams.value).then(response => {
    attendance_cfgList.value = (response.rows||[]).map(it=>{
      it.info=proxy.$tryToJson(it.vendorsParameter);
      return it;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    comId: null,
    projectId: data.currentProId,
    vendorsCode: 'uni',
    AppKey: '',
    AppSecret: '',
    projectGuid: '',
    vendorsParameter: null,
    enabled: 1,
    state: null,
    remark: null,
    isDel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("attendance_cfgRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  data.mode="add"
  reset();
  open.value = true;
  title.value = "添加考勤配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  data.mode="edit"
  reset();
  const _id = row.id || ids.value
  getAttendance_cfg(_id).then(response => {
    let obj=response.data;
    let info=proxy.$tryToJson(obj.vendorsParameter||"{}");    
    form.value =obj;
    form.value.AppKey=info.AppKey;
    form.value.AppSecret=info.AppSecret;
    form.value.projectGuid=info.projectGuid;
    open.value = true;
    title.value = "修改考勤配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["attendance_cfgRef"].validate(valid => {
    if (valid) {
      let objs=data.projects.filter(d=>d.id==form.value.projectId);
      form.value.comId=objs.length>0?objs[0].comId:userStore.currentComId;
      form.value.vendorsParameter = JSON.stringify({
        AppKey: form.value.AppKey,
        AppSecret: form.value.AppSecret,
        projectGuid: form.value.projectGuid,
      })
      form.value.enabled = form.value.enabled;
      if (form.value.id != null) {
        updateAttendance_cfg(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAttendance_cfg(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除考勤配置编号为"' + _ids + '"的数据项？').then(function () {
    return delAttendance_cfg(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/attendance_cfg/export', {
    ...queryParams.value
  }, `attendance_cfg_${new Date().getTime()}.xlsx`)
}
getProjectList();
getList();
</script>
