<template>
  <div class="bg-white 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_Vendor_Name') + ':'">
          <el-input v-model="form.Vendor_Name"></el-input>
        </el-form-item>

        <el-form-item :label="$t(prefix + 'label_Payment_Terms') + ':'">
          <el-select
            v-model="form.Payment_Terms"
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </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>

        <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>
        </el-form-item>
      </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"
            class="min-w-[200px]"
            filterable
            :loading="setAuditUserLoading"
            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="deleteSupplierFunc(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="total, prev, pager, next, jumper, sizes"
        @current-change="getList"
        @size-change="getList"
      />
    </div>
    <comp-edit
      v-model:visible="componentEditVisible"
      :item-data="dataForEdit"
      :category-data="categoryList"
      :currency-data="currencyList"
      @update:visible="getList"
    ></comp-edit>
    <comp-record
      :id="recordId"
      v-model:visible="componentRecordVisible"
      :status-list="statusList"
    ></comp-record>
    <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, watch } from 'vue'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElNotification,
  ElPagination,
  ElDialog,
  ElTooltip,
  ElMessage,
} from 'element-plus'
import compEdit from './components/edit.vue'
import compRecord from './components/record.vue'
import { $t } from '@/i18n/index'
import { getSupplierList, deleteSupplier } from '@/api/supplier.js'
import userAPI from '@/api/user'

defineComponent({
  name: 'ComponentIndentSupplierList',
})
const prefix = 'order.supplier.'
let componentEditVisible = ref(0) // 1 新增, 2编辑. 0关闭
let componentRecordVisible = ref(false) // 审核记录
let dataForEdit = ref({}) // 修改时用, 只是用作传递给子组件数据的变量
let recordId = ref('')
let loading = ref(false)
let categoryList = ref([
  '阿里巴巴平台付款',
  '70%定金',
  '50%定金',
  '40%定金',
  '30%定金',
  '全款',
  '月结',
  '半月结（两周结）',
])
const currencyList = ref([
  'AUD',
  'NZD',
  'CHY',
  'GBP',
  'EUR',
  'USD',
  'HKD',
  'CAD',
  'JPY',
  'SGD',
])
let form = ref({
  Vendor_Name: '',
  Payment_Terms: '',
  status: '',
} as any)
let total = ref(0)
let pageForm = ref({
  page: 1,
  limit: 20,
})
let list = ref([])
const mainTableConfig: any[] = [
  {
    label: 'order.supplier.label_Vendor_Name',
    field: 'Vendor_Name',
  },
  {
    label: 'order.supplier.label_Phone',
    field: 'Phone',
    width: '120',
  },
  {
    label: 'order.supplier.label_Payment_Terms',
    field: 'Payment_Terms',
    width: '110',
  },
  {
    label: '数据来源',
    field: 'fromwhere',
    width: '110',
  },
  {
    label: 'order.supplier.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 = {
    Vendor_Name: '',
    Payment_Terms: '',
    status: '',
  }
  pageForm.value = {
    page: 1,
    limit: 20,
  }
  total.value = 0
  getList()
}

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

const getList = () => {
  const p: any = Object.assign({}, pageForm.value, form.value)
  loading.value = true

  getSupplierList(p)
    .then((res: any) => {
      list.value =
        res.result?.data?.map((main: any) => {
          let status = Number(main.status)
          if (typeof status !== 'number') status = 0
          return {
            ...main,
            status,
          }
        }) || []

      total.value = res.result.total
    })
    .finally(() => {
      loading.value = false
    })
}

getList()

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 === 1)
      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: 1 })
    .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;
  }
}
</style>
