<script lang="ts" setup name="ListSource">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IlistQuery, IlistType, optionsType } from './list_interface'
import ListPriceAdd from './priceAdd.vue'
import { getDeletePrice, getPriceList, getTypeSelect, uploadPrice } from '@/api/system/price'
import { exportExcel } from '@/utils/exportXlsx'
// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  checkType: '',
  // model: '',
  priceItem: '',
  priceName: '',
  priceNo: '',
  priceType: '',
  offset: 1,
  limit: 10,
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref([])
// 总数
const total = ref(20)
// 表头
const columns = ref([
  {
    text: '价格编号',
    value: 'priceNo',
    width: '160',
  },
  {
    text: '价格名称',
    value: 'priceName',
    width: '90',
  },
  {
    text: '检校类型',
    value: 'checkType',
    width: '90',
  },
  // {
  //   text: '型号',
  //   value: 'model',
  // },
  {
    text: '类别',
    value: 'priceType',
  },
  {
    text: '项目',
    value: 'priceItem',
  },
  {
    text: '标准价格（元)',
    value: 'price',
    width: '120',
  },
  {
    text: '业务员折扣权限',
    value: 'operatorDiscountPermission',
    width: '130',
  },
  {
    text: '负责人折扣权限',
    value: 'directorDiscountPermission',
    width: '130',
  },
  {
    text: '依据标准',
    value: 'priceStandard',
    width: '90',
  },
  {
    text: '创建时间',
    value: 'createTime',
    width: '120',
  },
])

// 选中的内容
const checkoutList = ref([])
// 文件上传input
const fileRef = ref()
// 删除id
const deleteId = ref('')
// 详情id
const infoId = ref('0')
// 校验类型下拉框数组
const checkTypeOptions = ref<optionsType[]>([])
// 类别下拉框数组
const priceTypeOptions = ref<optionsType[]>([])
// 项目下拉框数组
const priceItemOptions = ref<optionsType[]>([])
const isPopconfirmShow = ref(false)
// 点击按钮
const buttonType = ref('')
const loadingTable = ref(false)
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  getPriceList(listQuery.value).then((response) => {
    list.value = response.data.records
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
fetchData(true)
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  priceName: string
}
// 点击编辑/详情
const handleEdit = (index: string, row: rowReturn, value: string) => {
  buttonType.value = value
  infoId.value = row.id
  show.value = false
}
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  console.log(row)
  ElMessageBox.confirm(
    `确认删除${row.priceName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getDeletePrice({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
const confirmEvent = () => {
  getDeletePrice({ id: deleteId.value }).then((res) => {
    if (res.code === 200) {
      isPopconfirmShow.value = false
      ElMessage.success('删除成功')
      fetchData(true)
    }
  })
}
const cancelEvent = () => {
  console.log('cancel!')
}
// 获取下拉框数据
const getOptions = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'checkType') {
      checkTypeOptions.value = res.data
    }
    else if (code === 'priceType') {
      priceTypeOptions.value = res.data
    }
    else if (code === 'priceItem') {
      priceItemOptions.value = res.data
    }
  })
}
getOptions('checkType')
getOptions('priceType')
getOptions('priceItem')
// 点击重置
const clearList = () => {
  listQuery.value = {
    checkType: '',
    priceItem: '',
    priceName: '',
    priceNo: '',
    priceType: '',
    offset: 1,
    limit: 10,
  }
}
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(true)
}
const { proxy } = getCurrentInstance() as any
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    exportExcel({
      json: list.value.map((item: IlistType, index: number) => ({ index: index + 1, priceNo: item.priceNo, priceName: item.priceName, checkType: item.checkType, priceType: item.priceType, priceItem: item.priceItem, price: item.price, operatorDiscountPermission: item.operatorDiscountPermission, directorDiscountPermission: item.directorDiscountPermission, priceStandard: item.priceStandard, createTime: item.createTime })),
      name: '价格列表',
      titleArr: ['序号', '价格编号', '价格名称', '检校类型', '类别', '项目', '标准价格（元)', '业务员折扣权限', '负责人折扣权限', '依据标准', '创建时间'],
      sheetName: 'sheet1',
    })
  }
  else if (checkoutList.value.length > 0) {
    exportExcel({
      json: checkoutList.value.map((item: IlistType, index: number) => ({ index: index + 1, priceNo: item.priceNo, priceName: item.priceName, checkType: item.checkType, priceType: item.priceType, priceItem: item.priceItem, price: item.price, operatorDiscountPermission: item.operatorDiscountPermission, directorDiscountPermission: item.directorDiscountPermission, priceStandard: item.priceStandard, createTime: item.createTime })),
      name: '价格列表',
      titleArr: ['序号', '价格编号', '价格名称', '检校类型', '类别', '项目', '标准价格（元)', '业务员折扣权限', '负责人折扣权限', '依据标准', '创建时间'],
      sheetName: 'sheet1',
    })
  }
  else {
    ElMessage.warning('暂无数据')
  }
  loading.close()
}
// 上传文件/批量导入
const onFileChange = (event: any) => {
  if (event.target.files[0].type === 'application/pdf') {
    if (event.target.files?.length !== 0) {
      // 创建formdata对象
      const fd = new FormData()
      fd.append('multipartFile', event.target.files[0])
      uploadPrice(fd).then((res) => {
        if (res.code === 200) {
          ElMessage.success('上传成功')
          fetchData(true)
        }
        else {
          ElMessage.error(res.message)
        }
      })
    }
  }
  else {
    ElMessage.error('请上传pdf格式')
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 upload = () => {
  fileRef.value.click()
}
const uploadAll = () => {
  upload()
}
const add = () => {
  buttonType.value = ''
  show.value = false
}
const exportAll = () => {
  exportExcelBtn()
}
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '溯源供方编号模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
</script>

<template>
  <div v-if="show">
    <app-container>
      <search-area
        :need-clear="true"
        @search="searchList" @clear="clearList"
      >
        <search-item>
          <el-input
            v-model.trim="listQuery.priceNo"
            placeholder="价格编号"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.priceName"
            placeholder="价格名称"
            clearable
          />
        </search-item>
        <search-item>
          <el-select
            v-model.trim="listQuery.checkType"
            clearable
            placeholder="检校类型"
            size="default"
            :disabled="buttonType === '详情'"
          >
            <el-option
              v-for="item in checkTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select
            v-model.trim="listQuery.priceType"
            clearable
            placeholder="类别"
            size="default"
            :disabled="buttonType === '详情'"
          >
            <el-option
              v-for="item in priceTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select
            v-model.trim="listQuery.priceItem"
            clearable
            placeholder="项目"
            size="default"
            :disabled="buttonType === '详情'"
          >
            <el-option
              v-for="item in priceItemOptions"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <el-button v-if="proxy.hasPerm('/measure/price/import')" type="primary">
            批量导入
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/price/mould')" type="primary">
            模板下载
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/price/add')" type="primary" @click="add">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/price/export')" type="primary" @click="exportAll">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/price/print')" v-print="printObj" type="primary">
            打印
          </el-button>
        </template>
        <input v-show="false" ref="fileRef" type="file" accept="pdf/*" @change="onFileChange">
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery"
          :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
        >
          <template #columns>
            <el-table-column label="操作" align="center" width="160">
              <template #default="{ row }">
                <el-button
                  v-if="proxy.hasPerm('/measure/price/edit')"
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row.$index, row, '编辑')"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row.$index, row, '详情')"
                >
                  详情
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/measure/price/delete')"
                  size="small"
                  link
                  type="danger"
                  @click="handleDelete(row.$index, row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
    <el-dialog
      v-model="isPopconfirmShow"
      title="确认框"
      width="30%"
    >
      <span>确定删除吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isPopconfirmShow = false">取消</el-button>
          <el-button type="primary" @click="confirmEvent">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <list-price-add
    v-else
    :info-id="infoId"
    :button-type="buttonType"
    @close="close"
  />
</template>

<style lang="scss" scoped>
.pagination {
  position: fixed;
  bottom: 0;
}

:deep .search-item {
  width: 11.5vw !important;
}
</style>
