<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import {
    Card,
    Button,
    Table,
    Form,
    FormItem,
    SelectOption,
    Select,
    Row,
    Col,
    Image,
    Input,
    Tooltip,
    message, Modal,
  } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { PictureUpload } from '/@/components/Upload';
  import type { FileItem } from '/@/components/Upload/src/upload';
  import { useRoute, useRouter } from 'vue-router';
  import {
    complainCloseApi,
    complainCommitApi,
    complainDetailApi,
    complainGetDownApi,
    complainLogsApi,
  } from '/@/api/complaints';
  import { useInitData } from '/@/hooks/data/useInitData';
  import { useUpload } from '/@/hooks/data/useUpload';
  import moment from 'moment';
  import {
    ComplainCloseData, ComplainGetDownData,
    ComplainGetDownItemData,
    ComplaintsData,
    ComplaintsDetailParams
  } from '/@/api/complaints/modal/complaintsModal';

  const route = useRoute();
  const router = useRouter();

  onMounted(() => {
    init();
  });

  const { optionsData: typeData } = useInitData<ComplainGetDownData>(complainGetDownApi);

  const typeItemData = ref<ComplainGetDownItemData[]>([]);

  const Textarea = Input.TextArea;
  const ImagePreviewGroup = Image.PreviewGroup;

  const columns = [
    { title: '投诉老师姓名', dataIndex: 'userName', key: 'userName' },
    { title: '学工号', dataIndex: 'teachNo', key: 'teachNo' },
    { title: '投诉老师手机号', dataIndex: 'userMobile', key: 'userMobile' },
    { title: '投诉老师邮箱', dataIndex: 'userEmail', key: 'userEmail' },
    { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
    { title: '投诉时间', dataIndex: 'tsTime', key: 'tsTime', slots: { customRender: 'tsTime' } },
    { title: '投诉供应商', dataIndex: 'supplier', key: 'supplier' },
    { title: '投诉原因', slots: { customRender: 'tsReason' }, key: 'tsReason', width: '240px' },
  ];

  const columns1 = [
    { title: '操作时间', dataIndex: 'operTime', key: 'operTime', slots: { customRender: 'operTime' } },
    { title: '操作人', dataIndex: 'name', key: 'name' },
    { title: '投诉分类', dataIndex: 'tsfl', key: 'tsfl' },
    { title: '问题描述', dataIndex: 'wtms', key: 'wtms' },
    { title: '投诉回复', dataIndex: 'busText', key: 'busText' },
    { title: '附件图片', key: 'attaches', slots: { customRender: 'attaches' } },
  ];

  const dataSource1 = ref<ComplainCloseData[]>([]);

  const form = ref<ComplaintsData>({ id: 0 });
  const fileList = ref<FileItem[]>([]);

  const rules = reactive({
    busType: [{ required: true, message: '投诉分类不能为空', trigger: ['change', 'blur'] }],
    busDesc: [{ required: true, message: '问题描述不能为空', trigger: ['change', 'blur'] }],
    busText: [
      { required: true, message: '投诉回复不能为空', trigger: ['change', 'blur'] },
      { max: 500, message: '投诉回复不能超过500字', trigger: ['change', 'blur'] },
    ],
  });

  const submitForm = ref<ComplaintsDetailParams>({
    id: 0,
  });

  const initDetailData = async () => {
    try {
      submitForm.value.id = Number(route.query.id);
      form.value = await complainDetailApi(submitForm.value.id);
    } catch (e) {
      console.log(e);
    }
  };

  const init = () => {
    submitForm.value.id = Number(route.query.id);
    initDetailData();
    initLogsData();
  };

  const initLogsData = async () => {
    try {
      dataSource1.value = await complainLogsApi(submitForm.value.id);
    } catch (e) {
      console.log(e);
    }
  };

  const handleSelect = (val) => {
    typeItemData.value = typeData.value.filter((el) => el.id === val)[0].children;
  };

  const cancelBtn = () => {
    router.go(-1);
  };
  const formRef = ref();

  const { validatorUpload } = useUpload();
  const submitBtn = async () => {
    try {
      await formRef.value.validate();
      await validatorUpload(fileList);
      const res = await complainCommitApi({
        ...submitForm.value,
        attaches: fileList.value.map((item) => item.response),
      });
      console.log(res);
      message.success('提交成功');
      submitForm.value = {
        busType: null,
        busText: '',
        id: 0,
      };
      fileList.value = [];
      init();
    } catch (e) {
      console.log(e);
    }
  };

  // 关闭投诉
  const closeBtn = () => {
    Modal.confirm({
      title: '系统提示',
      content: '确定要关闭投诉吗？',
      okText: '是否提交',
      onOk: async () => {
        try {
          const res = await complainCloseApi(submitForm.value.id);
          console.log(res);
          message.success('关闭成功');
          init();
        } catch (e) {
          console.log(e);
        }
      },
    });
  };
</script>

<template>
  <Card>
    <div>
      <div class="ant-descriptions-title flex-center" style="margin-bottom: 20px">
        <div style="flex: 1">投诉信息</div>
        <Button type="primary" @click="closeBtn" v-if="form.state != 3">关闭投诉</Button>
      </div>
      <Table :columns="columns" :dataSource="[form]" :scroll="{ x: 'max-content' }" :pagination="false" rowKey="id">
        <template #tsTime="{ record }">
          {{ moment(record.tsTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template #tsReason="{ record }">
          <Tooltip>
            <template #title>{{ record?.tsReason }}</template>
            <div class="two-overflow">{{ record?.tsReason }}</div>
          </Tooltip>
        </template>
      </Table>
    </div>
    <div v-if="form.state != 3">
      <div class="ant-descriptions-title" style="margin: 20px 0">投诉处理</div>
      <Form ref="formRef" layout="vertical" :model="submitForm" :rules="rules">
        <Row :gutter="20">
          <Col :span="16">
            <FormItem label="投诉分类" name="busType">
              <Select
                v-model:value="submitForm.busType"
                allow-clear
                placeholder="请选择"
                style="width: 100%"
                @change="handleSelect"
              >
                <SelectOption v-for="item in typeData" :key="item.id" :value="item.id">
                  {{ item.content }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="16">
            <FormItem label="问题描述" name="busDesc">
              <Select
                v-model:value="submitForm.busDesc"
                allow-clear
                placeholder="请选择"
                style="width: 100%"
                :disabled="!typeItemData.length"
              >
                <SelectOption v-for="item in typeItemData" :key="item.id" :value="item.id">
                  {{ item.content }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="16">
            <FormItem label="投诉回复" name="busText">
              <Textarea
                v-model:value="submitForm.busText"
                showCount
                :maxlength="500"
                :auto-size="{ minRows: 5 }"
              />
            </FormItem>
          </Col>
          <Col :span="16">
            <FormItem label="回复图片">
              <PictureUpload v-model:file-list="fileList">
                <div v-if="fileList.length < 9">
                  <plus-outlined />
                  <div class="ant-upload-text">上传</div>
                </div>
              </PictureUpload>
            </FormItem>
          </Col>
          <Col :span="24">
            <FormItem>
              <Button style="margin: 5px 0" type="primary" @click="submitBtn">回复</Button>
              <Button style="margin: 5px 0" @click="cancelBtn">取消</Button>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>
    <div>
      <div class="ant-descriptions-title" style="margin: 20px 0">处理记录</div>
      <Table
        :columns="columns1"
        :dataSource="dataSource1"
        :scroll="{ x: 'max-content' }"
        :pagination="false"
        rowKey="id"
      >
        <template #operTime="{ record }">
          {{ moment(record.operTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template #attaches="{ record }">
          <ImagePreviewGroup>
            <Image
              v-for="item in record.attaches"
              :key="item.uid"
              style="width: 50px; height: 50px"
              :width="50"
              :height="50"
              :src="item.src"
            />
          </ImagePreviewGroup>
        </template>
      </Table>
    </div>
  </Card>
</template>

<style lang="less" scoped>
  :deep(.ant-row) {
    flex-flow: column;
  }
  :deep(.ant-image) {
    margin: 0 5px;
    border-radius: 5px;
    overflow: hidden;
  }
</style>
