<script setup lang="ts">
import { ref, getCurrentInstance, reactive } from "vue";
import { useRouter } from "vue-router";
import request, { download } from '~/utils/request';
import { pick } from 'lodash-es';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { AxiosRequestConfig } from 'axios'

import topLeft from './components/top-left.vue'
import topRight from './components/top-right.vue'

// #region (constant)
const TABLE_KEY = 'xhs_id'
const URL_CUT = '/xdhq/hqgl_sbbx'
const URL_CUT_REF = ref(URL_CUT)
const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
const instance = getCurrentInstance()
const router = useRouter()
// #endregion

// #region (variable)
const loading_table = ref(true)
let whichDialogSubmit: 'add' | 'edit'
// #endregion

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'xhs_zcbh': string; // 资产编号
  'xhs_zcmc': string; // 资产名称
  'xhs_wxdd': string; // 维修地点
  'xhs_wxfs': string; // 维修方式
  'xhs_wxjg': string; // 维修结果
  'xhs_sqr': string; // 申请人
  'xhs_jsr': string; // 经手人
  'xhs_pzr': string; // 批准人
  'xhs_wxcs': string; // 维修次数
  'xhs_lb_mc': string; // 类别名称
  'xhs_lb_lj': string; // 类别路径
  'xhs_bxlb': string; // 报修类型
  'xhs_yy': string
}
// #endregion

// #region (props)
// #endregion

// #region (query row)
const queryForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleQueryFormBtn_search = () => {
  queryApi()
}
const handleQueryFormBtn_clear = () => {
  queryForm_Data.value = {}
  queryApi();
}
// #endregion

// #region (table selection)
const multipleSelection = ref<TYPE_TABLE_FIELD[]>([])
const handleSelectionChange = (val: TYPE_TABLE_FIELD[]) => {
  multipleSelection.value = val
}
// #endregion

// #region (table row)
const handleTableRowBtn_import = async ({ file }: { file: File }) => {
  const res = await API_MAP['import']({ file })
  if (res.code === '1') {
    queryApi()
    ElMessage.success(res.msg)
  }
}
const handleTableRowBtn_export = () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选导出文件');exportApi({[TABLE_KEY]:multipleSelection.value.map((item: TYPE_TABLE_FIELD)=>item[TABLE_KEY])?.join()})
}
const handleTableRowBtn_add = () => {
  whichDialogSubmit = 'add'
  dialogForm_Data.value = {}
  dialogVisible_addOrEdit.value = true
}
const handleTableRowBtn_delete = async () => {
  if(multipleSelection.value.length===0) return ElMessage.info('请先勾选文件');const resp = await deleteApi(multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY]));if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])
const DetailName = '-SBBX-DETAIL'
const DetailParam = 'aid'

const handleTableColBtn_edit = async (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  const res = await detailApi(scope.row[TABLE_KEY])
  dialogForm_Data.value = (res.data.one_info)
  dialogVisible_addOrEdit.value = true
}
const handleTableColBtn_audit = (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  dialogForm_Data.value = pick(scope.row, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_audit)])
  dialogVisible_audit.value = true
}
const handleTableColBtn_audit2 = (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  dialogForm_Data.value = pick(scope.row, [`${TABLE_KEY}`, ...Object.keys(dialogForm_Rules_audit)])
  dialogVisible_audit2.value = true
}
const handleTableColBtn_detail = (scope: { row: TYPE_TABLE_FIELD }) => {
  router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] } })
}
const handleTableColBtn_delete = async (scope: { row: TYPE_TABLE_FIELD }) => {
  const resp = await deleteApi(scope.row[TABLE_KEY]);if(resp.code!=='1')return;ElMessage.success('删除成功');
  queryApi()
}
const handleTableColBtn_drop = async (scope: { row: TYPE_TABLE_FIELD }) => {
  await editApi({ [TABLE_KEY]: scope.row[TABLE_KEY], xhs_wxjg: '3' })
  queryApi()
}

// #endregion

// #region (pagination)
const total = ref(0)
const limit = ref(5)

const currentPage = ref(1)
function handleCurrentChange() {
  queryApi()
}
// #endregion

// #region (dialog base)
const dialogForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleDialogFormBtn_submit = async (formRefKey: string, extendData?: Partial<TYPE_TABLE_FIELD>) => {
  const isValid = await (instance?.refs[formRefKey] as FormInstance).validate((valid: boolean) => valid)
  if (isValid) {
    const resp = await API_MAP[whichDialogSubmit](<TYPE_TABLE_FIELD>({ ...dialogForm_Data.value, ...extendData }))
    if(resp.code!=='1')return;ElMessage.success('操作成功');handleDialogFormBtn_cancel()
    queryApi()
  }
}
const handleDialogFormBtn_cancel = (formRefKey?: string) => {
  dialogVisible_addOrEdit.value = false
  dialogVisible_audit.value = false
  dialogVisible_audit2.value = false
}
// #endregion

// #region (dialog add/edit)
const dialogVisible_addOrEdit = ref<boolean>(false)

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'xhs_zcbh': { required: true, message: '资产编号不能为空', trigger: 'submit' },
  'xhs_zcmc': { required: true, message: '资产名称不能为空', trigger: 'submit' },
  'xhs_wxdd': { required: true, message: '维修地点不能为空', trigger: 'submit' },
  'xhs_wxfs': { required: true, message: '维修方式不能为空', trigger: 'submit' },
  'xhs_wxjg': { required: true, message: '维修结果不能为空', trigger: 'submit' },
  'xhs_sqr': { required: true, message: '申请人不能为空', trigger: 'submit' },
  'xhs_jsr': { required: true, message: '经手人不能为空', trigger: 'submit' },
  'xhs_pzr': { required: true, message: '批准人不能为空', trigger: 'submit' },
  'xhs_wxcs': { required: true, message: '维修次数不能为空', trigger: 'submit' },
  'xhs_lb_mc': { required: true, message: '类别名称不能为空', trigger: 'submit' },
  'xhs_lb_lj': { required: true, message: '类别路径不能为空', trigger: 'submit' },
  'xhs_bxlb': { required: true, message: '报修类型不能为空', trigger: 'submit' },
})
// #endregion

// #region (dialog audit)
const dialogVisible_audit = ref<boolean>(false)
const dialogVisible_audit2 = ref<boolean>(false)

const dialogForm_Field_audit = reactive<{
  FLAG: keyof TYPE_TABLE_FIELD,
  REASON: keyof TYPE_TABLE_FIELD
}>({
  FLAG: 'xhs_wxjg',
  REASON: 'xhs_yy'
})

const dialogForm_Ref_audit = ref<FormInstance>()
const dialogForm_Ref_audit2 = ref<FormInstance>()
const dialogForm_Rules_audit = reactive<FormRules>({
  // 'xhs_zcbh': { required: true, message: '资产编号不能为空', trigger: 'submit' },
  // 'xhs_zcmc': { required: true, message: '资产名称不能为空', trigger: 'submit' },
  // 'xhs_wxdd': { required: true, message: '维修地点不能为空', trigger: 'submit' },
  // 'xhs_wxfs': { required: true, message: '维修方式不能为空', trigger: 'submit' },
  'xhs_wxjg': { required: true, message: '维修结果不能为空', trigger: 'submit' },
  // 'xhs_sqr': { required: true, message: '申请人不能为空', trigger: 'submit' },
  // 'xhs_jsr': { required: true, message: '经手人不能为空', trigger: 'submit' },
  // 'xhs_pzr': { required: true, message: '批准人不能为空', trigger: 'submit' },
  // 'xhs_wxcs': { required: true, message: '维修次数不能为空', trigger: 'submit' },
  // 'xhs_lb_mc': { required: true, message: '类别名称不能为空', trigger: 'submit' },
  // 'xhs_lb_lj': { required: true, message: '类别路径不能为空', trigger: 'submit' },
  // 'xhs_bxlb': { required: true, message: '报修类型不能为空', trigger: 'submit' },
})

// #endregion

// #region (request api):
function queryApi() {
  loading_table.value = true
  return request({
    url: URL_CUT + '/index',
    data: {
      ...queryForm_Data.value,
      limit: limit.value,
      page: currentPage.value
    }
  }).then((response: { data: { total_rows: string, page_data: TYPE_TABLE_FIELD[] } }) => {
    const { data } = response
    total.value = parseInt(data.total_rows)
    tableData.value = data.page_data
    return response
  }).then(() => {
    loading_table.value = false
  })
}

function addApi(data: TYPE_TABLE_FIELD) {
  return request({
    url: URL_CUT + '/add',
    data: {
      [URL_SUBMIT_KEY]: data,
    }
  })
}

function editApi(data: Partial<TYPE_TABLE_FIELD>) {
  return request({
    url: URL_CUT + '/edit',
    data: {
      [TABLE_KEY]: data[TABLE_KEY],
      [URL_SUBMIT_KEY]: pick(data, ['xhs_zcbh', 'xhs_zcmc', 'xhs_wxdd', 'xhs_wxfs', 'xhs_wxjg', 'xhs_sqr', 'xhs_jsr', 'xhs_pzr', 'xhs_wxcs', 'xhs_lb_mc', 'xhs_lb_lj', 'xhs_bxlb', 'xhs_yy']),
    }
  })
}

function deleteApi(id: string | string[]) {
  return request({
    url: URL_CUT + '/delete',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function detailApi(id: string) {
  return request({
    url: URL_CUT + '/detail',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function importApi(data: { file: File }) {
  return request({
    $type: 'import',
    url: URL_CUT + '/import',
    data
  } as AxiosRequestConfig)
}

function exportApi(d) {
  return download(URL_CUT + '/index', {...queryForm_Data.value,...d})
}

const API_MAP = {
  query: queryApi,
  add: addApi,
  edit: editApi,
  delete: deleteApi,
  detail: detailApi,
  import: importApi,
  export: exportApi,
}
// #endregion

// #region (page init)
const echartsData = ref()
const echartsLoading = ref(true)
function init() {
  queryApi()
  request({ url: '/xdhq/hqgl_sbbx_stat/alyz' }).then(res => {
    echartsData.value = res.data
    echartsLoading.value = false
  })
}
init()
// #endregion

</script>

<template>
  <div class="mb-4 flex justify-between w-full h-232px">
    <template v-if="!echartsLoading">
      <topLeft :data="echartsData.wxgl"></topLeft>
      <div class="w-4"></div>
      <topRight :data="echartsData.sbwxqs"></topRight>
    </template>
  </div>
  <div class="card flex-grow flex flex-col">
    <el-form inline :model="queryForm_Data">
      <!-- <el-form-item label="关键字"><el-input v-model="queryForm_Data.keyword" ></el-input></el-form-item> -->
      <!-- <el-form-item label="资产编号">
        <el-input v-model="queryForm_Data.xhs_zcbh" clearable />
      </el-form-item> -->
      <el-form-item label="资产名称">
        <el-input v-model="queryForm_Data.xhs_zcmc" clearable />
      </el-form-item>
      <el-form-item label="维修地点">
        <el-input v-model="queryForm_Data.xhs_wxdd" clearable />
      </el-form-item>
      <!-- <el-form-item label="维修方式">
        <el-input v-model="queryForm_Data.xhs_wxfs" clearable />
      </el-form-item>
      <el-form-item label="维修结果">
        <el-select v-model="queryForm_Data.xhs_wxjg" clearable filterable>
          <el-option label="已维修" value="1" />
          <el-option label="待维修" value="2" />
          <el-option label="已报废" value="3" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="申请人">
        <el-input v-model="queryForm_Data.xhs_sqr" clearable />
      </el-form-item>
      <!-- <el-form-item label="经手人">
        <el-input v-model="queryForm_Data.xhs_jsr" clearable />
      </el-form-item>
      <el-form-item label="批准人">
        <el-input v-model="queryForm_Data.xhs_pzr" clearable />
      </el-form-item>
      <el-form-item label="维修次数">
        <el-input v-model="queryForm_Data.xhs_wxcs" clearable />
      </el-form-item>
      <el-form-item label="类别名称">
        <el-input v-model="queryForm_Data.xhs_lb_mc" clearable />
      </el-form-item>
      <el-form-item label="类别路径">
        <el-input v-model="queryForm_Data.xhs_lb_lj" clearable />
      </el-form-item>
      <el-form-item label="报修类型">
        <el-select v-model="queryForm_Data.xhs_bxlb" clearable filterable>
          <el-option label="电脑" value="1" />
          <el-option label="多媒体" value="2" />
          <el-option label="平台软件" value="3" />
          <el-option label="门窗五金" value="4" />
          <el-option label="水暖电气" value="5" />
          <el-option label="其他" value="6" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQueryFormBtn_search" type="primary">搜索</el-button>
        <el-button @click="handleQueryFormBtn_clear" type="warning">清空</el-button>
      </el-form-item>
    </el-form>
    <div class="divider"></div>
    <div>
      <!-- <import-button @success="queryApi" :url="URL_CUT_REF"></import-button> -->
      <el-button @click="handleTableRowBtn_export" type="success">导出</el-button>
      <el-button @click="handleTableRowBtn_add" type="primary">设备报修</el-button>
      <el-button @click="handleTableRowBtn_delete" type="danger">删除</el-button>
    </div>

    <div class="divider"></div>
    <div class="flex-auto">
      <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading_table"
        element-loading-background="#ffffff70">
        <el-table-column type="selection"></el-table-column>
        <!-- <el-table-column prop="xhs_zcbh" label="资产编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="xhs_zcmc" label="资产名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_bxlb" label="报修类型" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_wxdd" label="维修地点" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_wxfs" label="维修方式" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_wxjg" label="维修结果" width="auto" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.xhs_wxjg_option_k === '1'" class="text-green-500"> {{ scope.row.xhs_wxjg }}</span>
            <span v-else-if="scope.row.xhs_wxjg_option_k === '3'" class="text-red-500"> {{ scope.row.xhs_wxjg }}</span>
            <span v-else> {{ scope.row.xhs_wxjg }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="xhs_sqr" label="申请人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_jsr" label="经手人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_pzr" label="批准人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_wxcs" label="维修次数" width="auto" show-overflow-tooltip>
          <template #default="scope">
            <!-- <el-link type="primary" @click="router.push({ name: '-SBBX-BXW', params: { aid: scope.row.xhs_zcbh } })"> {{
                scope.row.xhs_wxcs
            }}次</el-link> -->
            <span> {{
                scope.row.xhs_wxcs
            }}次</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="xhs_lb_mc" label="类别名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhs_lb_lj" label="类别路径" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" fixed="right" width="160">
          <template #default="scope">
            <!-- <el-button link :auto-insert-space="false" @click="handleTableColBtn_edit(scope)" type="primary">编辑
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_audit(scope)" type="primary">审核
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_detail(scope)" type="primary">详情
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_delete(scope)" type="primary">删除
            </el-button> -->
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_audit(scope)" type="primary">已修
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_audit2(scope)" type="primary">未修
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_drop(scope)" type="primary">报废
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="flex justify-end mt-10 py-4">
      <el-pagination :page-size="limit" v-model:current-page="currentPage" @current-change="handleCurrentChange"
        background layout="total, prev, pager, next" :total="total" />
    </div>
  </div>
  <el-dialog v-model="dialogVisible_addOrEdit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
      label-width="120px">
      <!-- <el-form-item label="资产编号" prop="xhs_zcbh">
        <el-input v-model="dialogForm_Data.xhs_zcbh" clearable />
      </el-form-item> -->
      <el-form-item label="资产名称" prop="xhs_zcmc">
        <!-- <el-input v-model="dialogForm_Data.xhs_zcmc" clearable /> -->
        <remote-select url="/xdhq/hqgl_xcgl/index" :fields="['xhx_zcbh', 'xhx_zcmc']" v-model="dialogForm_Data.xhs_zcbh"
          v-model:modelName="dialogForm_Data.xhs_zcmc"></remote-select>
      </el-form-item>

      <el-form-item label="维修地点" prop="xhs_wxdd">
        <el-input v-model="dialogForm_Data.xhs_wxdd" clearable />
      </el-form-item>
      <el-form-item label="维修方式" prop="xhs_wxfs">
        <el-input v-model="dialogForm_Data.xhs_wxfs" clearable />
      </el-form-item>
      <!-- <el-form-item label="维修结果" prop="xhs_wxjg">
        <el-radio-group v-model="dialogForm_Data.xhs_wxjg">
          <el-radio label="1">已维修</el-radio>
          <el-radio label="2">待维修</el-radio>
          <el-radio label="3">已报废</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="申请人" prop="xhs_sqr">
        <el-input v-model="dialogForm_Data.xhs_sqr" clearable />
      </el-form-item>
      <el-form-item label="经手人" prop="xhs_jsr">
        <el-input v-model="dialogForm_Data.xhs_jsr" clearable />
      </el-form-item>
      <el-form-item label="批准人" prop="xhs_pzr">
        <el-input v-model="dialogForm_Data.xhs_pzr" clearable />
      </el-form-item>
      <el-form-item label="维修次数" prop="xhs_wxcs">
        <el-input v-model="dialogForm_Data.xhs_wxcs" clearable />
      </el-form-item>
      <!-- <el-form-item label="类别名称" prop="xhs_lb_mc">
        <el-input v-model="dialogForm_Data.xhs_lb_mc" clearable />
      </el-form-item>
      <el-form-item label="类别路径" prop="xhs_lb_lj">
        <el-input v-model="dialogForm_Data.xhs_lb_lj" clearable />
      </el-form-item> -->
      <el-form-item label="报修类型" prop="xhs_bxlb">
        <!-- <el-select v-model="dialogForm_Data.xhs_bxlb" clearable filterable>
          <el-option label="电脑" value="1" />
          <el-option label="多媒体" value="2" />
          <el-option label="平台软件" value="3" />
          <el-option label="门窗五金" value="4" />
          <el-option label="水暖电气" value="5" />
          <el-option label="其他" value="6" />
        </el-select> -->
        <remote-dictionary-select to="BXLB" v-model="dialogForm_Data.xhs_bxlb"></remote-dictionary-select>
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit', { xhs_wxjg: '2' })" type="primary">提交
        </el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogVisible_audit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_audit" :rules="dialogForm_Rules_audit" label-width="120px">
      <el-form-item label="状态">
        <el-radio-group v-model="dialogForm_Data[dialogForm_Field_audit.FLAG]">
          <el-radio label="1">成功</el-radio>
          <el-radio label="2">失败</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="原因" v-show="dialogForm_Data[dialogForm_Field_audit.FLAG] === '2'">
        <el-input type="textarea" v-model="dialogForm_Data[dialogForm_Field_audit.REASON]" :rows="5" />
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_audit')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_audit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogVisible_audit2" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_audit2" :rules="dialogForm_Rules_audit" label-width="120px">
      <el-form-item label="原因">
        <el-input type="textarea" v-model="dialogForm_Data[dialogForm_Field_audit.REASON]" :rows="5" />
      </el-form-item>
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_audit2', { [dialogForm_Field_audit.FLAG]: '2' })"
          type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_audit2')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
