<template>
  <div class="page-indent-list py-4 px-2 shadow max-w-[1800px] mx-auto">
    <el-form
      ref="searchForm"
      :inline="true"
      :model="form"
      label-width="110px"
    >
      <div class="flex flex-wrap items-center search-form">
        <el-form-item :label="$t(prefix + 'label_project_name') + ':'">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item :label="$t(prefix + 'label_category') + ':'">
          <el-cascader
            v-model="form.category"
            :options="categoryList"
            :props="{ label: 'name', value: 'id' }"
          ></el-cascader>
        </el-form-item>

        <el-form-item :label="$t(prefix + 'label_status') + ':'">
          <el-select
            v-model="form.status"
            clearable
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <div class="flex items-center btn-group">
          <el-button
            size="small"
            type="primary"
            @click="search"
          >
            {{ $t('btn_query') }}
          </el-button>
          <el-button
            size="small"
            type="default"
            @click="reset"
          >
            {{ $t('btn_reset') }}
          </el-button>
        </div>
      </div>
    </el-form>

    <div class="mb-2 flex justify-between">
      <el-button
        size="small"
        type="primary"
        @click="componentEditVisible = 1"
      >
        {{ $t('btn_add') }}
      </el-button>
      <el-form inline>
        <el-form-item label="审核人:">
          <el-select
            v-model="auditUser"
            :loading="setAuditUserLoading"
            class="min-w-[200px]"
            filterable
            placeholder="可搜索"
            size="small"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :value="user.id"
              :label="`${user.name} (${user.username})`"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-tooltip content="保存审核人">
            <el-button
              type="primary"
              size="small"
              :loading="setAuditUserLoading"
              @click="setAuditUser"
            >
              保存
            </el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      ref="tableIndent"
      :header-cell-style="{ backgroundColor: '#F2F6FC' }"
      :row-style="{ backgroundColor: '#F2F6FC' }"
      :data="list"
      default-expand-all
      border
    >
      <el-table-column type="index"></el-table-column>
      <el-table-column
        v-for="value in mainTableConfig"
        :key="value.field"
        :align="value.align || 'center'"
        :width="value.width || ''"
        :prop="value.field"
        :label="$t(value.label)"
      >
        <template #default="scope">
          <div v-if="value.type === 'imageList'">
            <img
              v-if="scope.row[value.field].length"
              style="width: 100%"
              :src="scope.row[value.field][0]"
              @click="imgClick(scope.row[value.field][0])"
            />
          </div>
          <div v-else-if="value.field === 'status'">
            <div>
              {{ getStatusLabel(scope.row[value.field]) }}
            </div>
            <el-button
              size="small"
              type="primary"
              link
              @click="openRecord(scope.row)"
            >
              {{ $t(prefix + 'label_audit_detail') }}
            </el-button>
          </div>
          <div
            v-else
            class="table-cell-content"
            :style="value.style || {}"
          >
            {{ scope.row[value.field] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        width="220"
        :label="$t('table_operation')"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :disabled="scope.row.status === 0"
            @click="edit(scope.row)"
          >
            {{ $t('btn_edit') }}
          </el-button>
          <el-button
            size="small"
            type="warning"
            :disabled="scope.row.status !== 0"
            @click="examine(scope.row)"
          >
            {{ $t('btn_audit') }}
          </el-button>
          <el-button
            :disabled="scope.row.status !== 2"
            size="small"
            type="danger"
            @click="deleteProductFunc(scope.row)"
          >
            {{ $t('btn_delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end my-4">
      <el-pagination
        v-show="total > 0"
        v-model:current-page="pageForm.page"
        v-model:page-size="pageForm.limit"
        v-model:total="total"
        layout="prev, pager, next, jumper, sizes"
        @current-change="getList"
        @size-change="getList"
      />
    </div>
    <comp-edit
      v-model:visible="componentEditVisible"
      :product-data="dataForEdit"
      :category-data="categoryList"
      @update:visible="getList"
    ></comp-edit>
    <comp-record
      :id="recordId"
      v-model:visible="componentRecordVisible"
      :status-list="statusList"
    ></comp-record>
    <comp-examine
      v-model:visible="componentExamineVisible"
      :category-data="categoryList"
      :data-for-examine="dataForEaxmine"
      @update:visible="getList"
    ></comp-examine>
    <el-dialog
      v-model="bigImageVisible"
      style="margin: 5vh auto"
      width="800"
    >
      <div class="flex justify-center">
        <img
          :src="currentBigImage"
          style="max-width: 100%; height: auto"
          alt=""
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, inject, watch } from 'vue'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElNotification,
  ElPagination,
  ElCascader,
  ElDialog,
  ElTooltip,
  ElMessage,
} from 'element-plus'
import compEdit from './components/edit.vue'
import compRecord from './components/record.vue'
import compExamine from './components/examine.vue'
import { $t } from '@/i18n/index'
import { getProductList, deleteProduct } from '@/api/product.js'
import { getCategoryTree } from '@/api/indent.js'
import userAPI from '@/api/user'

defineComponent({
  name: 'ComponentIndentProductList',
})

const $mediaRegExp = inject('mediaRegExp') as RegExp
const prefix = 'order.product.'
let componentEditVisible = ref(0) // 1 新增, 2编辑. 0关闭
let componentRecordVisible = ref(false) // 审核记录
let componentExamineVisible = ref(false) // 审核
let dataForEaxmine = ref({})
let dataForEdit = ref({}) // 修改时用, 只是用作传递给子组件数据的变量
let recordId = ref('')
let loading = ref(false)
let categoryList = ref([])
let form = ref({
  name: '',
  category: [],

  status: '',
} as any)
let total = ref(0)
let pageForm = ref({
  page: 1,
  limit: 20,
})
let list = ref([])
const mainTableConfig: any[] = [
  {
    label: 'order.product.label_img',
    type: 'imageList',
    field: 'images',
    width: '120',
  },
  {
    label: 'order.product.label_product_code',
    field: 'product_sku',
    width: '180',
  },
  {
    label: 'order.product.label_name',
    field: 'product_name',
    // style: 'text-align: left'
  },
  {
    label: 'order.product.label_status',
    field: 'status',
    width: '110',
    style: 'font-weight: bold;',
  },
  {
    label: 'table_operator',
    field: 'admin_name',
    width: '90',
  },
  {
    label: 'table_operated_time',
    field: 'update_time',
    width: '180',
  },
]
const statusList = [
  {
    value: 0,
    label: '待审核',
  },
  {
    value: 1,
    label: '审核通过',
  },
  {
    value: 2,
    label: '审核不通过',
  },
]

const search = () => {
  pageForm.value = {
    page: 1,
    limit: 20,
  }
  getList()
}

const getStatusLabel = (value: number) => {
  const temp = statusList.filter((i: any) => i.value === value)
  return temp.length ? temp[0].label : '-'
}
const reset = () => {
  form.value = {
    name: '',
    category: [],
    status: 0,
  }
  pageForm.value = {
    page: 1,
    limit: 20,
  }
  total.value = 0
  getList()
}

const edit = (row: any) => {
  dataForEdit.value = row
  componentEditVisible.value = 2
}
const deleteProductFunc = (row: any) => {
  ElMessageBox.confirm('将删除该商品, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteProduct({ id: row.id }).then((res: any) => {
      if (res.code === 1) {
        getList()
        ElNotification({
          title: '删除成功',
          message: '正在刷新数据',
          duration: 3000,
        })
      }
    })
  })
}
const examine = (row: any) => {
  dataForEaxmine.value = row
  componentExamineVisible.value = true
}
const openRecord = (row: any) => {
  recordId.value = row.id
  componentRecordVisible.value = true
}

const getList = () => {
  const p: any = Object.assign({}, pageForm.value)
  const temp = { k: '', category: '', status: '' }
  if (form.value.category.length) {
    temp.category = form.value.category.join(',')
  }
  if (form.value.name?.length) {
    temp.k = form.value.name.trim()
  }
  if (statusList.map((i) => i.value).includes(form.value.status)) {
    temp.status = `${form.value.status}`
  }
  if (Object.keys(temp).length) {
    p.searchParams = JSON.stringify(temp)
  }
  loading.value = true

  getProductList(p)
    .then((res: any) => {
      list.value =
        res.result?.data?.map((main: any) => {
          const t =
            typeof main.images === 'string'
              ? `${main.images}`.split(',').filter((i: string) => i.length > 0)
              : []
          let status = Number(main.status)
          if (typeof status !== 'number') status = 0
          return {
            ...main,
            status,
            images: t.map((i: string) => {
              return $mediaRegExp.test(i)
                ? i
                : import.meta.env.VITE_APP_OSS_PREFIX + i
            }),
          }
        }) || []

      total.value = res.result.total
    })
    .finally(() => {
      loading.value = false
    })
}
const getCategoryList = () => {
  getCategoryTree().then((response: any) => {
    const res = response.result
    categoryList.value = res
  })
}
getList()
getCategoryList()

const currentBigImage = ref('')
const bigImageVisible = ref(false)
const imgClick = (url: string) => {
  currentBigImage.value = url
  bigImageVisible.value = true
}
watch(bigImageVisible, () => {
  if (!bigImageVisible.value) currentBigImage.value = ''
})
const userList = ref([] as any[])
const getUserListFunc = () => {
  userAPI
    .getUserList({
      page: 1,
      limit: 200,
    })
    .then((res: any) => {
      if (res.code !== 1) {
        return
      }
      userList.value =
        res.result.data
          .filter((i: any) => i.status === 1)
          .sort((a: any, b: any) => a.name.localeCompare(b.name)) || []
    })
}
getUserListFunc()
const auditUser = ref('')
const getCurrentAuditUser = () => {
  userAPI.getAuditUser().then((res: any) => {
    console.log(res, 'res')
    if (
      res.code === 1 &&
      Array.isArray(res.result.data) &&
      res.result.data.length
    ) {
      const temp = res.result.data.filter((i: any) => i.type === 2)
      console.log(temp, 'temp')
      if (temp.length) auditUser.value = temp[0].check_id
    }
  })
}
getCurrentAuditUser()
const setAuditUserLoading = ref(false)
const setAuditUser = () => {
  setAuditUserLoading.value = true
  userAPI
    .setAuditUser({ check_id: auditUser.value, type: 2 })
    .then((res: any) => {
      console.log(res, 'res')
      if (res.code === 1) {
        ElMessage.success('设置成功')
      }
    })
    .finally(() => (setAuditUserLoading.value = false))
}
</script>

<style lang="scss" scoped>
.search-form {
  .el-input,
  .el-select,
  .el-date-editor {
    width: 220px;
  }
  .btn-group {
    margin: 0 0 22px 8px;
  }
}
</style>
