<script lang="ts" setup name="CreateOrCheck">
import { onMounted, reactive, ref } from 'vue'
import type { Ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { IdeviceListQuery, Iform } from './receive'
import SelectDeviceDialog from './selectDeviceDialog.vue'
import ReceiveDialog from '@/views/device/receive/receiveDialog.vue'
const $route = useRoute()
const typeValue = ref()
const deviceName = ref()
const isMulti = ref(false) // 是否批量添加(允许多选)
const selectIndex = ref()
const { proxy } = getCurrentInstance() as any
const dialogSelectDiviceVisible = ref(false) // 控制选择设备对话框显隐
const isShowDialog = ref(false) // 控制审批对话框显隐
const total = ref(20)// 总数
const approveOpinion = ref() // 审批意见：1同意2驳回0拒绝
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const haveApproveLimits = ref(true)// 是否有审批权限
const isStart = ref(false)// 是否是发起人
// 选中的内容
const checkoutList = ref([])
// 表单数据
const form = ref({
  company: '申请单位', // 申请单位
  person: '申请人1', // 申请人
  time: '1', // 领用时间
  state: '', // 申请说明
})
const ruleFormRef = ref<FormInstance>() as any
const list = ref([])// 表格数据
// 查询条件
const listQuery: Ref<IdeviceListQuery> = ref({
  name: '', // 仪器名称
  number: '', // 设备编号
  version: '', // 型号
  scope: '', // 测量范围
  dep: '', // 使用部门
  person: '', // 使用人
  status: '', // 管理状态
  date: '', // 有效日期
  offset: 1,
  limit: 10,
})
const columns = [
  {
    text: '仪器名称',
    value: 'name',
  },
  {
    text: '设备编号',
    value: 'number',
  },
  {
    text: '型号',
    value: 'version',
  },
  {
    text: '测量范围',
    value: 'scope',
  },
  {
    text: '使用部门',
    value: 'dep',
  },
  {
    text: '使用人',
    value: 'person',
  },
  {
    text: '管理状态',
    value: 'status',
  },
  {
    text: '有效日期',
    value: 'date',
  },
]
const rules = reactive<FormRules>({
  company: [
    { required: true, message: '请输入申请单位', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  person: [
    { required: true, message: '请输入申请人', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  time: [
    {
      type: 'date',
      required: true,
      message: '请选择领用时间',
      trigger: 'change',
    },
  ],
})

const handleClick = (val: string) => {
// 1同意，2驳回，0拒绝，3提交，4撤回
  if (val === '3') { // 提交
    ruleFormRef.value.validate((valid: boolean) => {
      if (valid) {
        console.log('submit!')
      }
      else {
        console.log('表单提交失败')
      }
    })
  }
  else if (val === '1') {
    isShowDialog.value = true
    approveOpinion.value = '1'
  }
  else if (val === '2') {
    isShowDialog.value = true
    approveOpinion.value = '2'
  }
  else if (val === '0') {
    isShowDialog.value = true
    approveOpinion.value = '0'
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  // fetchData(true)
}
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 删除行
const delRow = () => {
  console.log(checkoutList.value)

  if (checkoutList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    // 调删除接口
    checkoutList.value.forEach((item: IdeviceListQuery) => {
      // if (!item.name && !item.number) {
      list.value.forEach((element, index) => {
        if (element.name === item.name && element.number === item.number) {
          list.value.splice(index, 1)
        }
      })
      // }
    })
  }
}
// 增加行
const addRow = () => {
  list.value.push({
    name: '', // 仪器名称
    number: '', // 设备编号
    version: '', // 型号
    scope: '', // 测量范围
    dep: '', // 使用部门
    person: '', // 使用人
    status: '', // 管理状态
    date: '', // 有效日期
  })
}
// 点击选择
const handleSelect = (index: number, row: IdeviceListQuery) => {
  dialogSelectDiviceVisible.value = true
  isMulti.value = false
  selectIndex.value = index
  console.log('选中的index', row)
}
// 点击批量添加
const multiAdd = () => {
  dialogSelectDiviceVisible.value = true
  isMulti.value = true
}
const $router = useRouter()
// 点击关闭
const close = () => {
  $router.push('/receive/applyList')
}
// 选择设备对话框关闭
const closeDialog = () => {
  dialogSelectDiviceVisible.value = false
  isShowDialog.value = false
}
// 选择好设备了
const updateDeviceConfirm = (val: any) => {
  if (isMulti.value) {
    val.forEach((item: any) => {
      list.value.push(item)
    })
  }
  else {
    list.value.splice(selectIndex.value, 1, val[0])
  }
}

onMounted(() => {
  typeValue.value = $route.query.typeValue
  deviceName.value = $route.query.deviceName
})
</script>

<template>
  <app-container>
    <detail-page :title="typeValue === 'detail' && deviceName ? `${deviceName}-详情` : `设备领用申请-${textMap[typeValue]}`">
      <template #btns>
        <el-button v-if="haveApproveLimits && !isStart && typeValue === 'add'" type="primary" @click="handleClick('1')">
          同意
        </el-button>
        <el-button v-if="haveApproveLimits && !isStart && typeValue === 'add'" type="primary" @click="handleClick('2')">
          驳回
        </el-button>
        <el-button v-if="haveApproveLimits && !isStart && typeValue === 'add'" type="primary" @click="handleClick('0')">
          拒绝
        </el-button>
        <el-button v-if="isStart && typeValue === 'add'" type="primary" @click="handleClick('3')">
          提交
        </el-button>
        <el-button v-if="isStart && typeValue === 'add'" type="primary" @click="handleClick('4')">
          撤回
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
    </detail-page>
    <div class="create-check">
      <div class="top-info">
        <div class="form-area">
          <el-form
            ref="ruleFormRef"
            :model="form"
            label-width="120px"
            :rules="rules"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请单位" prop="company">
                  <el-input v-model="form.company" clearable :disabled="typeValue === 'detail'" />
                </el-form-item>
                <el-form-item label="申请人" prop="person">
                  <el-input v-model="form.person" clearable :disabled="typeValue === 'detail'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="领用时间" prop="time">
                  <el-date-picker
                    v-model="form.time"
                    type="datetime"
                    placeholder="请选择领用时间"
                    :disabled="typeValue === 'detail'"
                  />
                </el-form-item>
                <el-form-item label="申请说明">
                  <el-input v-model="form.state" type="textarea" clearable :disabled="typeValue === 'detail'" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <detail-block title="设备领用列表">
        <template #btns>
          <el-button v-if="typeValue !== 'detail'" type="primary" @click="multiAdd">
            批量添加
          </el-button>
          <el-button v-if="typeValue !== 'detail'" type="primary" @click="addRow">
            增加行
          </el-button>
          <el-button v-if="typeValue !== 'detail'" type="info" @click="delRow">
            删除行
          </el-button>
        </template>
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery"
          :is-showmulti-select="typeValue === 'detail' ? false : true" @change="changePage" @multiSelect="handleSelectionChange"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column v-if="typeValue !== 'detail'" label="操作" align="center" width="60" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleSelect(scope.$index, scope.row)"
                >
                  选择
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </detail-block>

      <detail-block title="审批流程">
        <el-timeline>
          <el-timeline-item timestamp="2018/4/12" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/12 20:46</p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item timestamp="2018/4/3" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/3 20:46</p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item timestamp="2018/4/2" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/2 20:46</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </detail-block>
    </div>
    <select-device-dialog
      :dialog-select-divice-visible="dialogSelectDiviceVisible"
      :is-multi="isMulti"
      @closeDialog="closeDialog"
      @updateDeviceConfirm="updateDeviceConfirm"
    />

    <!-- 同意、驳回、拒绝对话框显示 -->
    <receive-dialog
      :is-show-dialog="isShowDialog"
      :approve-opinion="approveOpinion"
      @closeDialog="closeDialog"
    />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.create-check {
  margin-top: 10px;

  .top-info {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding-right: 10px;
    border-radius: 10px;
    background-color: #fff;
    // padding: 10px;

    .title-button {
      display: flex;
      align-items: center;

      &::before {
        content: "";
        flex: 1;
      }

      .button-group {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
    }

    .form-area {
      margin-top: 40px;
    }
  }
}
</style>
