<template>
  <div class="content">
    <el-row :gutter="10" class="mb8">
      <el-col :span="4">
        <el-input style="height:36px" v-model="queryParams.deptid" placeholder="请输入申请矿井"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input style="height:36px" v-model="queryParams.jnickname" placeholder="请输入经办人"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input style="height:36px" v-model="queryParams.fnickname" placeholder="请输入分管领导"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input style="height:36px" v-model="queryParams.dnickname" placeholder="请输入单位负责人"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input style="height:36px" v-model="queryParams.applyid" placeholder="请输入申请编号"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-button size="default" plain :icon="Search" type="cyan" @click="GetSearch">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-button size="default" :icon="Plus" type="primary" @click="handleApply">申请</el-button>
        <el-button size="default" :icon="Edit" type="success" @click="handleEdit" :disabled="selected.length !== 1 || (selected[0].status !== '0' && selected[0].status !== '1')">修改
        </el-button>
        <el-button size="default" :icon="Delete" type="danger" @click="handleDelete" :disabled="selected.length !== 1 || (selected[0].status !== '0' && selected[0].status !== '1')">删除
        </el-button>
      </el-col>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData.value"
        :select-on-indeterminate="true"
        @selection-change="handleSelectionChange"
        height="700"
        ref="tableDataRef"
        :row-key="RowKey"
      >
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
        <el-table-column label="序号" fixed>
          <template #default="scope">
            <span>{{(queryParams.pageNum-1)*queryParams.pageSize+(scope.$index + 1)}} </span>
          </template>
        </el-table-column>
        <el-table-column label="申请编号" sortable align="center" prop="applyid" min-width="160">
        </el-table-column>
        <el-table-column label="申请矿井" sortable align="center" prop="deptid" min-width="120" :formatter="formatterDept">
        </el-table-column>
        <el-table-column label="使用工作面" sortable align="center" prop="surface" min-width="120">
        </el-table-column>
        <el-table-column label="接续工作面" sortable align="center" prop="continueSurfaceNum" min-width="120">
        </el-table-column>
        <el-table-column label="经办人" sortable align="center" prop="jnickname" min-width="200"/>
        <el-table-column label="申请日期" sortable align="center" prop="date" min-width="150">
          <template #default="scope">
            <span>{{ scope.row.year3 }}-{{ scope.row.month3 }}-{{ scope.row.day3 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="驳回原因" sortable align="center" prop="bremark" min-width="150"/>
        <el-table-column label="状态" sortable align="center" prop="status" width="180" :formatter="formatterStatus"/>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog v-model="dialogApply" :title="dialogTitle" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="applyForm" :rules="rules" label-width="110px">
        <el-form-item label="工作面" prop="surface">
          <el-input
            type="text"
            v-model="applyForm.surface"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="date1">
          <el-date-picker type="date" placeholder="请选择开始时间" v-model="applyForm.date1" value-format="YYYY-MM-DD" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="date2">
          <el-date-picker type="date" placeholder="请选择结束时间" v-model="applyForm.date2" value-format="YYYY-MM-DD" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接续工作面" prop="continueSurfaceNum">
          <el-input
            type="text"
            v-model="applyForm.continueSurfaceNum"
            placeholder="请输入接续工作面，没有请填写无"
          />
        </el-form-item>
        <el-form-item label="使用维修说明" prop="requirement1">
          <el-input
            type="textarea"
            v-model="applyForm.requirement1"
            placeholder="请输入使用维修说明1"
          />
          <el-input
            type="textarea"
            v-model="applyForm.requirement2"
            placeholder="请输入使用维修说明2"
            style="margin-top: 10px"
          />
          <span style="color:red">注：1.使用单台设备明确到货日期，使用成套设备明确发货及截止日期。<br/>2.改变设备结构件及控制系统必须向集团相关部室提出申请，批准后实施。</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="applyAdd(formRef)">确 定</el-button>
        <el-button @click="applyCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" name="Sbsq" setup>
import {
	ref,
	reactive,
	watchEffect,
	getCurrentInstance
} from "vue";
import { listApply, getApply, delApply, updateApply, addApply } from "@/api/flowable/demo/wzhbgnew";
import { listDept } from "@/api/system/dept";
// import treeSelect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import Treeselect from "vue3-treeselect"
// import 'vue3-treeselect/dist/vue3-treeselect.css'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, ElForm, ElTable } from "element-plus";

// 引入全局方法
const { proxy } = getCurrentInstance() as any;

const queryForm = ref<InstanceType<typeof ElForm>>();
const formRef = ref<FormInstance>()
const tableDataRef = ref<InstanceType<typeof ElTable>>();

const tableData = reactive<any>({
  value: []
})

const total = ref<number>(10)

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
})

const statusOptions = reactive<any>([{
  dictValue: 0,
  dictLabel: "驳回"
}, {
  dictValue: 1,
  dictLabel: "待审核"
}, {
  dictValue: 2,
  dictLabel: "待单位负责人审核"
}, {
  dictValue: 3,
  dictLabel: "待设备科审核"
}, {
  dictValue: 4,
  dictLabel: "发放中"
},{
  dictValue: 5,
  dictLabel: "待分公司分管领导审批"
},{
  dictValue: 6,
  dictLabel: "审核通过"
}, {
  dictValue: 7,
  dictLabel: "发放完成"
}])

const ffStatusOptions = reactive([{
  dictValue: 0,
  dictLabel: "驳回"
}, {
  dictValue: 1,
  dictLabel: "待审核"
}, {
  dictValue: 2,
  dictLabel: "待乙方负责人审核"
}, {
  dictValue: 3,
  dictLabel: "待发放确认"
}, {
  dictValue: 4,
  dictLabel: "发放已确认"
},{
  dictValue: 5,
  dictLabel: "已回交"
},{
  dictValue: 6,
  dictLabel: "待分管领导审核"
},{
  dictValue: 7,
  dictLabel: "回交中"
}])

const selected = reactive<any>({
  value: []
})

const title = ref<string>("")

const form = reactive<any>({})

const loading = ref<boolean>(false)
// 是否显示弹出层
const open = ref<boolean>(false)
const openDetail = ref<boolean>(false)

const apply = reactive<any>({})

//中间参数
const queryParams2 = reactive<any>({})

const dialog = ref<boolean>(false)

const total3 = ref<null>(null)

const dialogApply = ref<boolean>(false)

const applyForm = reactive<any>({
  date1: '',
  year1: '',
  month1: '',
  day1: '',
  date2: '',
  year2: '',
  month2: '',
  day2: '',
  date3: '',
  year3: '',
  month3: '',
  day3: '',
})

const equipmentList = reactive<any>({
  value: []
})

const rules = reactive<FormRules>({
  // applyid: [{required: true, message: "不能为空", trigger: "blur,change"}],
  surfaceid: [{required: true, message: "工作面不能为空", trigger: "blur,change"}],
  continueSurfaceNum: [{required: true, message: "接续工作面不能为空", trigger: "blur,change"}],
  date1: [{required: true, message: "开始时间不能为空", trigger: "blur,change"}],
  date2: [{required: true, message: "结束时间不能为空", trigger: "blur,change"}],
})

const surfaceList = reactive<any>({
  value: []
})

const currentApply = reactive<any>({})

const currentFF = reactive<any>({})

const refreshKey = ref<string>("")

const dialogTitle = ref<string>("")

const ffListDialog = ref<boolean>(false)

const ffList = reactive<any>({
  value: []
})

const workspaceWarn = ref<boolean>(false)

const deptTree = reactive<any>({
  value: []
})

const deptList = reactive<any>({
  value: []
})

const surfaceStatusOptions = reactive<any>({
  value: []
})

const surfaceOpen = ref<boolean>(false)

const applyFormSurfaceShow = ref<boolean>(false)

const formatterStatus = (row: any, column: any) => {
  return proxy.selectDictLabel(statusOptions, row.status);
}

const formatterFFStatus = (row: any, column: any) => {
  return proxy.selectDictLabel(ffStatusOptions, row.status);
}

const formatterDept = (row: any, column: any) => {
  return proxy.selectDictLabel(deptList.value, row.deptid);
}

const handleSelectionChange = (val: any) => {
  selected.value = val
}
//查询部门
const getDeptList = () => {
  listDept().then((response) => {
    deptTree.value = proxy.handleTree(response.data.filter((e: any) => e.deptType !=1 && e.deptType != 5 && e.deptType != 6 && e.deptType != 4 && e.status=='0'), "deptId")
    deptList.value = response.data.map((item: any) => {
      return {
        dictValue: item.deptId,
        dictLabel: item.deptName
      }
    });
  });
}
getDeptList()

// 确定按钮
const cancel = () => {
  open.value = false;
  openDetail.value = false;
}

const handleApply = () => {
  // applyForm = {}
  proxy.resetForm(formRef);
  dialogTitle.value = "设备申请";
  dialogApply.value = true
}

const handleEdit = (row: any) => {
  if (row.id || selected.value.length === 1) {
    let id = row.id ? row.id : selected.value[0].id
    getApply({id: id}).then((res: any) => {
      // applyForm = res.data
      applyForm.date1 = applyForm.year1 + "-" + applyForm.month1 + "-" + applyForm.day1
      applyForm.date2 = applyForm.year2 + "-" + applyForm.month2 + "-" + applyForm.day2
      proxy.resetForm(formRef);
      dialogTitle.value = "设备申请修改";
      dialogApply.value = true
    })
  } else {
    proxy.$message({
      type: 'error',
      message: '请选择一条申请!'
    });
  }
}

const handleDelete = () => {
  proxy.$confirm('是否删除此申请?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (selected.value.length === 1) {
      delApply(selected.value[0].id).then((res: any) => {
        getList()
        proxy.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    } else {
      proxy.$message({
        type: 'error',
        message: '请选择一条申请!'
      });
    }
  }).catch(() => {

  });
}

const applyAdd = async (formEl: FormInstance | undefined) => {
  if(applyFormSurfaceShow.value){
    proxy.msgWarning("请完善工作面信息")
    return
  }
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      // 日期处理
      let date1 = applyForm.date1.split('-')
      applyForm.year1 = date1[0]
      applyForm.month1 = date1[1]
      applyForm.day1 = date1[2]
      let date2 = applyForm.date2.split('-')
      applyForm.year2 = date2[0]
      applyForm.month2 = date2[1]
      applyForm.day2 = date2[2]  
      let now = new Date();
      if (applyForm.id !== undefined && applyForm.id !== null && applyForm.id !== "") {
        // this.applyForm.updateTime = now.toLocaleString('zh', { hour12: false });
        updateApply(applyForm).then((res: any) => {
          proxy.$message.success("操作成功")
          dialogApply.value = false
          getList()
        })
      } else {
        applyForm.year3 = now.getFullYear()
        applyForm.month3 = now.getMonth()+1
        applyForm.day3 = now.getDate()
        // this.applyForm.createTime = now.toLocaleString('zh', { hour12: false });
        addApply(applyForm).then((res: any) => {
          proxy.$message.success("操作成功")
          dialogApply.value = false
          getList()
        })
      }
    }
  })
}

const applyCancel = () => {
  dialogApply.value = false
}

const getList = () => {
  selected.value = []
  listApply(queryParams).then((response: any) => {
    tableData.value = response.rows
    total.value = response.total
    console.log(tableData.value, 111);
    tableDataRef.value?.clearSelection();
  });
}
getList()

const GetSearch = () => {
  getList();
}

const RowKey = (row: any) => {
  return row.id;
}

/** 转换单位数据结构 */
const normalizer = (node: any) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.deptId,
    label: node.deptName,
    children: node.children,
  };
}

proxy.getDicts("sys_nomal_disable").then((response: any) => {
  surfaceStatusOptions.value = response.data;
})
</script>
<style scoped lang="scss">
.content {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 0;
  margin-bottom: 0;
  padding-top: 0 !important;
}

.card {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.box-card1 {
  width: 300px;
  font-size: 14px;
  margin-bottom: 20px;

}

.box-card1 ::v-deep .el-card__body {
  padding-bottom: 10px;
}

.el-col {
  margin-bottom: 15px;

  .name {
    font-size: 15px;
  }
}
.equipmentTable {
  width: 100%;
  border-spacing: 0;

  td {
    border-left: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    text-align: center;

    input {
      border: none;
      width: 100%;
      height: 35px;
    }

    input:focus-visible {
      outline: none;
    }
  }

  tr td:nth-child(4) input {
    width: 50px;
  }

  tr:first-child td {
    border-top: 1px solid #DCDFE6;
  }

  tr td:last-child {
    border-right: 1px solid #DCDFE6;
    width: 20px;
  }
}

::v-deep .select-trigger {
  .el-input {
    .el-input__wrapper {
      height: 36px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
