<template>
  <ElDialog
    v-model="visible"
    :title="title"
    top="6vh"
    width="1400px"
    :close-on-click-modal="false"
  >
    <ElTabs v-model="activeName" class="demo-tabs">
      <ElTabPane label="打版信息" name="first">
        <div v-loading="loading" class="review-info">
          <div class="modals-image">
            <div class="modals-image-title">
              <span>模特图</span>
            </div>
            <div style="display: flex; gap: 10px; flex: 1; overflow: hidden">
              <div class="color-images-list">
                <div
                  v-for="(item, index) of row?.imageList"
                  :key="index"
                  class="color-image-item"
                  @mouseover="onMouseover(item.imagePath)"
                >
                  <img :src="item.imagePath" alt="" class="img-sign" />
                </div>
              </div>
              <div class="modals-image-big">
                <img
                  :src="mainImageUrl || row?.imageList[0]?.imagePath"
                  alt=""
                  class="img-sign"
                />
              </div>
            </div>
          </div>
          <div class="modals-image-version">
            <div
              style="
                height: 60px;
                font-size: 30px;
                line-height: 60px;
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span
                :style="{
                  cursor: 'pointer',
                  color: version === 1 ? '#eee' : '#333',
                }"
                style="height: 100%; display: inline-block"
                title="上一版"
              >
                <el-icon style="height: 100%" @click="prev"
                  ><CaretLeft
                /></el-icon>
              </span>
              <span>第{{ version }}版</span>
              <span
                :title="
                  version === versionList?.length ? '添加新版本' : '下一版'
                "
                style="height: 100%; display: inline-block"
              >
                <el-icon
                  :style="{
                    color: versionList?.length == version ? '#eee' : '#333',
                    cursor: 'pointer',
                  }"
                  style="height: 100%"
                  @click="next"
                  ><CaretRight />
                </el-icon>
              </span>
            </div>
            <div
              v-loading="uploadLoading"
              element-loading-text="加载中..."
              class="image-wrap"
            >
              <div class="image-wrap-url">
                <img :src="versionImageUrl" alt="" class="img-sign" />
                <div
                  class="flex items-center"
                  v-if="
                    row?.state == 301 ||
                    (row?.state == 401 && lastVersion == version)
                  "
                >
                  <span style="width: 50px; font-size: 16px">面料: </span>
                  <el-input
                    v-model="fabric"
                    v-if="
                      row?.state == 301 ||
                      (row?.state == 401 && lastVersion == version)
                    "
                  ></el-input>
                </div>
                <div class="flex items-center" v-else>
                  <span style="width: 50px; font-size: 16px">面料: </span>
                  <span style="font-size: 15px; font-weight: 600">{{
                    fabric
                  }}</span>
                </div>
              </div>
              <div
                style="
                  height: 100%;
                  overflow: hidden;
                  display: flex;
                  flex-direction: column;
                "
              >
                <div class="color-image-list">
                  <div
                    v-for="(item, index) of versionImageList"
                    :key="index"
                    class="color-image-item"
                    @mousemove="onRightMouseover(item?.imagePath)"
                  >
                    <img :src="item.imagePath" alt="" class="img-sign" />
                    <span
                      v-if="
                        lastVersion === version &&
                        (row?.state === '301' || row?.state === '401')
                      "
                      class="remove"
                      @click="remove(index)"
                    >
                      <el-icon><Close /></el-icon>
                    </span>
                  </div>
                </div>
                <input
                  ref="fileInputRef"
                  type="file"
                  style="display: none"
                  multiple
                  @change="onChange"
                />
                <div
                  v-if="
                    !detailable &&
                    lastVersion === version &&
                    (row?.state === '301' || row?.state === '401')
                  "
                  class="color-image-item-icon-plus"
                  @click="addImage"
                >
                  <el-icon><Plus /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </ElTabPane>
      <ElTabPane
        v-if="
          row?.state === '601' || row?.state === '701' || row?.state === '901'
        "
        label="上传稿件"
        name="second"
      >
        <div v-loading="loading" class="review-info">
          <div class="modals-image">
            <div class="modals-image-title">
              <span>模特图</span>
            </div>
            <div style="display: flex; gap: 10px; flex: 1; overflow: hidden">
              <div class="color-images-list">
                <div
                  v-for="(item, index) of row?.colorImageList"
                  :key="index"
                  class="color-image-item"
                >
                  <img :src="item" alt="" class="img-sign" />
                </div>
              </div>
              <div class="modals-image-big">
                <img :src="row?.mainImage" alt="" class="img-sign" />
              </div>
            </div>
          </div>
          <div class="price-form">
            <div class="modals-image-title">
              <span>上传稿件</span>
            </div>
            <ElForm ref="priceFormRef" :model="priceForm" label-width="100px">
              <ElFormItem
                label="稿件"
                prop="craftImage"
                :rules="[{ required: true, message: '请上传稿件' }]"
              >
                <UploadImage
                  v-model="priceForm.craftImage"
                  :disabled="
                    detailable || row?.state === '701' || row?.state === '901'
                  "
                ></UploadImage>
              </ElFormItem>
              <ElFormItem
                label="大货单价"
                prop="bulkUnitPrice"
                :rules="[{ required: true, message: '请输入大货单价' }]"
              >
                <ElInput
                  v-model="priceForm.bulkUnitPrice"
                  clearable
                  type="number"
                  :disabled="
                    detailable || row?.state === '701' || row?.state === '901'
                  "
                  placeholder="大货单价"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="测试单价" prop="testUnitPrice">
                <ElInput
                  v-model="priceForm.testUnitPrice"
                  placeholder="测试单价"
                  clearable
                  :disabled="
                    detailable || row?.state === '701' || row?.state === '901'
                  "
                ></ElInput>
              </ElFormItem>
              <!-- <ElFormItem
                label="货期(天)"
                prop="deliveryDay"
                :rules="[{ type: 'number', message: '货期必须为数字值' }]"
              >
                <ElInput
                  v-model.number="priceForm.deliveryDay"
                  placeholder="货期(天)"
                  clearable
                ></ElInput>
              </ElFormItem> -->
              <ElFormItem label="备注" prop="priceNote">
                <ElInput
                  v-model="priceForm.priceNote"
                  type="textarea"
                  :disabled="
                    detailable || row?.state === '701' || row?.state === '901'
                  "
                  placeholder="备注"
                ></ElInput>
              </ElFormItem>
              <ElFormItem
                v-if="priceForm.priceOpinion"
                label="审核意见"
                prop="priceOpinion"
              >
                <p v-dompurify-html="priceForm.priceOpinion"></p>
              </ElFormItem>
            </ElForm>
          </div>
        </div>
      </ElTabPane>
      <ElTabPane label="详情" name="third">
        <div class="detail-info">
          <ElRow :gutter="20">
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">编码</span>
                <span class="value">{{ row?.code || '--' }}</span>
              </div>
            </ElCol>
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">SKU</span>
                <span class="value">{{ row?.homeSku || '--' }}</span>
              </div>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">货号</span>
                <span class="value">{{ row?.code || '--' }}</span>
              </div>
            </ElCol>
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">负责人</span>
                <span class="value">{{ row?.personInChargeName || '--' }}</span>
              </div>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">紧急程度</span>
                <span class="value" :style="renderStyle(row?.urgentLevel)">{{
                  renderLevel(row?.urgentLevel)
                }}</span>
              </div>
            </ElCol>
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">期望完成日期</span>
                <span class="value">{{ row?.expectCompleteTime || '--' }}</span>
              </div>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">承诺完成日期</span>
                <span class="value">{{
                  row?.promiseCompleteTime || '--'
                }}</span>
              </div>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :span="12">
              <div class="detail-info-item">
                <span class="label">样板要求</span>
                <p v-dompurify-html="row?.requirement"></p>
              </div>
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>
      <ElTabPane label="审核意见" name="four">
        <div class="audit-opinion">
          <template v-for="(item, index) in versionList" :key="index">
            <div
              v-if="item.examineImages.length && item.opinion"
              :key="index"
              class="opinion_version"
            >
              <p>
                {{ item.updateTime }}
                {{ item.examinePeopleName }} 审核了样版，版本为{{
                  item.version
                }}，审核结果为【{{ item.state == 2 ? '通过 】' : ''
                }}{{ item.state == 3 ? '不通过】' : '' }}
                ，审核意见如下：
              </p>
              <p v-dompurify-html="item.opinion"></p>
            </div>
          </template>
        </div>
      </ElTabPane>
    </ElTabs>
    <template v-if="!detailable" #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="visible = false">取消</el-button>
        <el-button
          v-if="row?.state === '301' || row?.state === '401'"
          size="large"
          type="primary"
          @click="submitReview"
          >提交审核</el-button
        >
        <el-button
          v-if="row?.state === '601'"
          size="large"
          type="primary"
          @click="submitReviewPriceInfo"
          >保存</el-button
        >
        <template v-if="row?.state === '501'">
          <el-button size="large" type="warning" @click="notPassReview"
            >不通过</el-button
          >
          <el-button size="large" type="success" @click="passReview"
            >通过</el-button
          >
        </template>
      </div>
    </template>
  </ElDialog>
  <el-dialog
    v-model="innerVisible"
    width="800px"
    title="审核意见"
    append-to-body
  >
    <wangEditor
      ref="wangeditorRef"
      v-model="opinion"
      placeholder="审核意见"
      height="400px"
      filename="files"
    ></wangEditor>
    <template #footer>
      <el-button @click="innerVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitAudit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, defineEmits, defineProps, ref, watch } from 'vue'
import { CaretLeft, CaretRight, Plus, Close } from '@element-plus/icons-vue'
import { showError } from '@/utils/ui'
import { uploadImageApi } from '@/api/common'
import {
  TypesettingListData,
  VersionImageList,
  VersionList,
  PriceForm,
} from '@/types/api/typesetting'
import {
  getExamineInfoByIdApi,
  submitReviewApi,
  submitReviewOpinionApi,
  submitReviewPriceInfoApi,
  getPriceDetailApi,
} from '@/api/typesetting'
import wangEditor from '@/components/WangEditor.vue'
import UploadImage from '@/components/UploadImage.vue'
const props = defineProps({
  modelValue: Boolean,
  title: String,
  row: Object,
  detailable: Boolean,
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const visible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})
watch(visible, (val) => {
  if (val) {
    if (props.row?.state === '601' && !props.detailable) {
      activeName.value = 'second'
    } else {
      activeName.value = 'first'
    }
    mainImageUrl.value = props.row?.mainImage
  }
})
const opinion = ref('')
const fabric = ref('')
const loading = ref(false)
const submitReview = async () => {
  // if (versionImageList.value.length === 0) {
  //   showError('请上传图片')
  //   return
  // }
  const BtnIndex = Number(version.value - 1)
  // 检查 imagePath 是否为空或 null
  if (
    versionImageList.value.length == 0 ||
    (versionImageList.value[BtnIndex] &&
      !versionImageList.value[BtnIndex].imagePath)
  ) {
    ElMessage.warning('请上传样版图片')
    return
  }
  // 检查 fabric 是否为空或 null
  if (!fabric.value) {
    ElMessage.warning('请填写对应的面料')
    return
  }
  loading.value = true
  try {
    const res = await submitReviewApi(
      props.row?.id,
      version.value,
      versionImageList.value,
      fabric.value,
    )
    ElMessage.success(res.message)
    emit('update:modelValue', false)
    emit('refresh')
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const activeName = ref('first')
const innerVisible = ref(false)
const version = ref(1)
const prev = () => {
  if (version.value > 1) {
    version.value -= 1
    const item = versionList.value.find((item) => item.version == version.value)
    if (item) {
      versionImageList.value = item.examineImages
      fabric.value = item?.fabric || ''
      versionImageUrl.value = item.examineImages[0]?.imagePath
    } else {
      versionImageList.value = []
      versionImageUrl.value = ''
      fabric.value = ''
    }
  }
}
const next = () => {
  if (versionList.value.length == version.value) return
  version.value += 1
  const item = versionList.value.find((item) => item.version == version.value)
  if (item) {
    versionImageList.value = item.examineImages
    fabric.value = item?.fabric || ''
    versionImageUrl.value = item.examineImages[0]?.imagePath
  } else {
    versionImageList.value = []
    versionImageUrl.value = ''
    fabric.value = ''
  }
}
const versionImageUrl = ref('')
const versionImageList = ref<VersionImageList[]>([])
const fileInputRef = ref()
const addImage = () => {
  fileInputRef.value.click()
}
const uploadLoading = ref(false)
const onChange = async (files: Event) => {
  const fileList = (files.target as HTMLInputElement).files
  if (!fileList) return

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const requestList: Promise<any>[] = []
  for (let i = 0; i < fileList.length; i++) {
    const file = fileList[i]
    const formData = new FormData()
    formData.append('file', file)
    formData.append('businessType', 'product')
    requestList.push(uploadImageApi(formData))
  }
  uploadLoading.value = true
  fileInputRef.value.value = ''
  try {
    const res = await Promise.all(requestList)
    const createImage: VersionImageList[] = []
    res.forEach((item, index) => {
      const imgInfo = {
        sort: versionImageList.value.length + index,
        imagePath: item.filePath,
      }
      createImage.push(imgInfo)
    })
    versionImageList.value = [...versionImageList.value, ...createImage]
    versionImageUrl.value = versionImageList.value[0].imagePath ?? ''
    // versionImageList.value = res.map((item) => {
    //   return {
    //     imagePath: item?.filePath,
    //     sort: versionImageList.value.length + 1,
    //   }
    // })
    // versionImageUrl.value = res[0].filePath ?? ''
  } catch (e) {
    console.error(e)
  } finally {
    uploadLoading.value = false
  }
}
const versionList = ref<VersionList[]>([])
const lastVersion = ref<number | null>(null)
const getExamineInfo = async (data: TypesettingListData) => {
  try {
    const res = await getExamineInfoByIdApi(data.id)
    if (!res.data) return
    versionList.value = res.data
    // if (data?.state === '301' || data?.state === '401') {
    versionList.value.push({
      version: versionList.value.length + 1,
      examineImages: [],
    })
    // }
    if (res.data.length > 0) {
      version.value = res.data[res.data.length - 1].version ?? 1
      lastVersion.value = res.data[res.data.length - 1].version ?? 1
      versionImageList.value = res.data[res.data.length - 1]?.examineImages
      versionImageUrl.value =
        res.data[res.data.length - 1]?.examineImages[0]?.imagePath
      fabric.value = res.data[res.data.length - 1].fabric || ''
    } else {
      versionImageList.value = []
      versionImageUrl.value = ''
      fabric.value = ''
    }
  } catch (e) {
    console.error(e)
  }
}
const examine = ref(false)
const notPassReview = () => {
  innerVisible.value = true
  examine.value = false
  opinion.value = ''
}
const passReview = () => {
  innerVisible.value = true
  examine.value = true
  opinion.value = ''
}
const submitAudit = async () => {
  if (opinion.value === '') {
    showError('请输入审核意见')
    return
  }
  loading.value = true
  try {
    const res = await submitReviewOpinionApi(
      props.row?.id,
      examine.value,
      opinion.value,
      versionList.value[versionList.value.length - 1]?.id,
    )
    ElMessage.success(res.message)
    emit('update:modelValue', false)
    emit('refresh')
    innerVisible.value = false
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const priceForm = ref<PriceForm>({})
const priceFormRef = ref()
const submitReviewPriceInfo = async () => {
  try {
    await priceFormRef.value?.validate()
  } catch {
    return
  }
  loading.value = true
  try {
    const res = await submitReviewPriceInfoApi(props.row?.id, priceForm.value)
    ElMessage.success(res.message)
    emit('update:modelValue', false)
    emit('refresh')
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const reset = async () => {
  await priceFormRef.value?.resetFields()
}
const remove = (index: number) => {
  versionImageList.value.splice(index, 1)
  if (versionImageList.value.length > 0) {
    versionImageUrl.value = versionImageList.value[0].imagePath ?? ''
  } else {
    versionImageUrl.value = ''
  }
}
const renderLevel = (level: number) => {
  if (level === 3) {
    return '非常紧急'
  } else if (level === 2) {
    return '紧急'
  } else if (level === 1) {
    return '一般'
  } else {
    return '--'
  }
}
const renderStyle = (level: number) => {
  if (level === 3) {
    return {
      color: '#F54D66',
      fontWeight: 'bold',
    }
  } else if (level === 2) {
    return {
      color: '#FDC834',
      fontWeight: 'bold',
    }
  } else if (level === 1) {
    return {
      color: '#5DE088',
      fontWeight: 'bold',
    }
  } else {
    return {
      color: '#333',
    }
  }
}
const getPriceDetail = async (data: TypesettingListData) => {
  try {
    const res = await getPriceDetailApi(data.id)
    priceForm.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const mainImageUrl = ref<string>('')
const onMouseover = (url: string) => {
  mainImageUrl.value = url
}
const onRightMouseover = (url: string | undefined) => {
  versionImageUrl.value = url || ''
}
defineExpose({ getExamineInfo, reset, getPriceDetail })
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
.review-info {
  display: flex;
  gap: 10px;
  height: 600px;
}
.modals-image {
  flex: 1;
  display: flex;
  flex-direction: column;
  .color-image-item {
    width: 60px;
    height: 60px;
    border: 1px solid #eee;
    margin-bottom: 5px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.modals-image-title {
  font-size: 30px;
  text-align: center;
  height: 60px;
  line-height: 60px;
}
.modals-image-version,
.price-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.image-wrap {
  display: flex;
  gap: 10px;
  flex: 1;
  overflow: hidden;
  .image-wrap-url {
    flex: 1;
    text-align: center;
    img {
      width: 100%;
      height: 90%;
      object-fit: contain;
    }
  }
  .color-image-item-icon-plus {
    width: 60px;
    height: 60px;
    border: 1px solid #eee;
    cursor: pointer;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    i {
      color: #777;
      font-size: 24px;
    }
  }

  .color-image-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    // flex: 1;
    // overflow-y: auto;
    margin-bottom: 10px;
  }
  .color-image-item {
    width: 60px;
    height: 60px;
    border: 1px solid #eee;
    cursor: pointer;
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
  }
}

.modals-image-big {
  flex: 1;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
.detail-info {
  height: 600px;
  overflow-y: auto;
  :deep(.el-row) {
    height: 30px;
    line-height: 30px;
  }
}
.detail-info-item {
  .value {
    color: #333;
  }
  .label {
    display: inline-block;
    width: 100px;
    text-align: right;
    margin-right: 6px;
  }
}
.audit-opinion {
  height: 600px;
}
.img-sign[src=''],
.img-sign:not([src]) {
  opacity: 0;
}
.remove {
  position: absolute;
  right: 0px;
  top: 0px;
  font-size: 20px;
  cursor: pointer;
  border: 1px solid #333;
  border-radius: 50%;
  width: 10px;
  height: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  i {
    font-size: 12px;
  }
}
.color-images-list{
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
