<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="投诉标题" prop="title">-->
<!--        <el-input-->
<!--            v-model="queryParams.title"-->
<!--            placeholder="请输入投诉标题"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="投诉人姓名" prop="name">-->
<!--        <el-input-->
<!--            v-model="queryParams.name"-->
<!--            placeholder="请输入投诉人姓名"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="联系方式" prop="phone">-->
<!--        <el-input-->
<!--            v-model="queryParams.phone"-->
<!--            placeholder="请输入联系方式"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="身份证号" prop="card">
        <el-input
            v-model="queryParams.card"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="图片文件" prop="fileId">-->
<!--        <el-input-->
<!--            v-model="queryParams.fileId"-->
<!--            placeholder="请输入图片文件"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['basicData:complain:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['basicData:complain:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['basicData:complain:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['basicData:complain:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="complainList" height="650" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="投诉类型" align="center" prop="type">
        <template #default="scope">
          {{dickMap.get(scope.row.type)}}
        </template>
      </el-table-column>
      <el-table-column label="投诉标题" align="center" prop="title" />
      <el-table-column label="投诉内容" align="center" prop="content" />
      <el-table-column label="投诉人姓名" align="center" prop="name" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="身份证号" align="center" prop="card" />
      <el-table-column label="图片文件" align="center" prop="files" width="220" >
        <template #default="scope">
          <img :src="baseURL+ scope.row.files[0]?.fileUrl" style="width: 200px;" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['basicData:complain:edit']"
          >修改</el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basicData:complain:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改投诉对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="complainRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="投诉类型" prop="type">
<!--          <el-input v-model="form.type" placeholder="请输入投诉类型" />-->
          <el-select v-model="form.type" placeholder="请输入投诉类型">
            <el-option
                v-for="dict in dickArr"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="投诉标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入投诉标题" />
        </el-form-item>
        <el-form-item label="投诉内容">
          <el-input v-model="form.content" :min-height="192" type="textarea"/>
        </el-form-item>
        <el-form-item label="投诉人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入投诉人姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="身份证号" prop="card" :rules="cardRules">
          <el-input v-model="form.card" placeholder="请输入身份证号" />
        </el-form-item>
<!--        <el-form-item label="图片文件" :rules="imagesRules" prop="fileId">-->
<!--          <el-upload ref="uploadRef"-->
<!--                     :limit="3"-->
<!--                     :multiple="true"-->
<!--                     accept=".jpg, .png"-->
<!--                     :headers="upload.headers"-->
<!--                     :action="upload.url + '?updateSupport=' + upload.updateSupport"-->
<!--                     :disabled="upload.isUploading"-->
<!--                     :data="{moduleName:'投诉模块'}"-->
<!--                     :before-upload="beforeUpload"-->
<!--                     :on-success="handleFileSuccess"-->
<!--                     :auto-upload="false"-->
<!--                     drag>-->
<!--            <el-icon class="el-icon&#45;&#45;upload"><upload-filled /></el-icon>-->
<!--            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
<!--            <template #tip>-->
<!--              <div class="el-upload__tip text-center">-->
<!--                <span>仅允许导入.jpg, .png格式文件。</span>-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item label="图片文件" prop="files">
          <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :action="upload.url"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :multiple="true"
              accept=".jpg, .png"
              :before-upload="beforeUpload"
              :on-success="handleFileSuccess"
              :headers="upload.headers"
              :data="{moduleName:'投诉模块'}"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Complain">
import {listComplain, getComplain, delComplain, addComplain, updateComplain, getDict} from "@/api/basicData/complain";
import {Editor} from "@wangeditor/editor-for-vue";
import {ElMessage} from "element-plus";
import {computed, reactive, ref} from "vue";
import {getToken} from "../../../utils/auth";
import {likeQueryMethod} from "../../../utils/likeQueryMethod";
import {delImgById} from "../../../api/basicData/complain";

const baseURL = import.meta.env.VITE_APP_BASE_API
const { proxy } = getCurrentInstance();

const complainList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const beforeUpdateLimit = ref(0);
const dickArr = ref([]);


const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

let dickMap = new Map();

const handleRemove = (uploadFile, uploadFiles) => {
  delImgById(uploadFile.id).then(res=>{
    if(res.code === 200){
      proxy.$modal.msgSuccess("删除成功");
    }
  })
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}





const cardRules = [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/, message: '身份证号格式不正确' },
  ]

const handleFileSuccess = (e,v)=>{
  beforeUpdateLimit.value = beforeUpdateLimit.value-1
  console.log(beforeUpdateLimit.value);
  form.value.files.push(e.data)
  if(e.code == 200){
    ElMessage({
      type:"success",
      message:e.msg
    })
  }
}
const task = ()=>{
  proxy.$refs["complainRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateComplain(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          beforeUpdateLimit.value = 0
        });
      } else {
        addComplain(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          beforeUpdateLimit.value = 0
        });
      }
    }
  });
}
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/commonFile/uploadFile',
})

const data = reactive({
  form: {
    id: null,
    type: null,
    title: null,
    content: null,
    name: null,
    phone: null,
    card: '',
    fileId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    files:[]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    title: null,
    content: null,
    name: null,
    phone: null,
    card: '',
    fileId: null,
    files:[]
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询投诉列表 */
function getList() {
  loading.value = true;
  let toServerObj = likeQueryMethod('card', queryParams.value.card, queryParams.value.pageNum, queryParams.value.pageSize);
  listComplain(toServerObj).then(response => {
    complainList.value = response.records ;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    title: null,
    content: null,
    name: null,
    phone: null,
    card: '',
    fileId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    files:[]
  };
  proxy.resetForm("complainRef");
  beforeUpdateLimit.value = 0
  fileList.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const init =async ()=>{
  let res = await getDict('crm_complaint_category');
  dickArr.value = res.data;
  dickArr.value.forEach((item)=>{
    let k = item.dictValue;
    let v = item.dictLabel;
    dickMap.set(k,v)
  })
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加投诉";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getComplain(id).then(response => {
    form.value = response.data.data;
    fileList.value = response.data.data.files.map(item=>{
      return{
        name:item.fileName,
        url: import.meta.env.VITE_APP_BASE_API + item.fileUrl,
        id:item.id
      }
    })
    open.value = true;
    title.value = "修改投诉";
  });
}

const beforeUpload = ()=>{
  beforeUpdateLimit.value = beforeUpdateLimit.value +1;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['uploadRef'].submit()
  if(beforeUpdateLimit.value == 0){
    task()
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids2 = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除投诉编号为"' + ids2 + '"的数据项？').then(function() {
    return delComplain(ids2);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basicData/complain/export', {
    ...queryParams.value
  }, `complain_${new Date().getTime()}.xlsx`)
}

getList();
init()
</script>
