<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-dropdown trigger="click">
        <el-button type="primary" size="small">
          其它<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Download" @click="handleExport" v-hasPermi="['business:deposit:export']">
              导出</el-dropdown-item>
            <!-- <el-dropdown-item type="warning" size="small" icon="Download" @click="handleArea"
              v-hasPermi="['business:deposit:export']"> area</el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!-- <el-button type="warning" size="small" icon="Download" @click="handleExport"
        v-hasPermi="['business:deposit:export']">导出</el-button> -->
      <!--<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="78px">
      <el-form-item>
        <el-radio-group v-model="queryRadio" size="small" @change="radioChangeHandler">
          <el-radio-button label="全部" />
          <el-radio-button label="流转反馈" />
          <el-radio-button label="驳回反馈" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="客户名称：" prop="companyName">
        <el-input v-model="queryParams.companyName" style="width: 150px" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:" v-hasPermi="['business:feedback:person']"> 
        <el-switch v-model="oneself" @change="handleOneself" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="operation" @click="moreSearch = true">更多</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div v-if="flag && flag2 && tenant.versionId !== '4'">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="全部" name="first">
        </el-tab-pane>
        <el-tab-pane label="我的" name="second">
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 列表区 -->
    <el-table v-loading="loading" :data="list" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column
align="center"
type="index"
label="序号"
width="50"
></el-table-column> -->
      <el-table-column label="客户名称" prop="companyName" min-width="250" align="center" />
      <el-table-column label="来源" align="center" prop="fromCompanyName" min-width="130"
        v-if="tenant.versionId === '4'" />
      <el-table-column label="受委托方" align="center" prop="toTenantName" min-width="130"
        v-if="tenant.versionId !== '4'" />
      <el-table-column label="纳税性质" prop="taxType" align="center" min-width="90" />
      <el-table-column label="收票月份" prop="provinceCode" min-width="80" align="center">
        <template #default="scope">
          <span>{{ scope.row.year + "-" + scope.row.month }}</span>
        </template>
      </el-table-column>
      <el-table-column label="反馈信息" prop="remark" min-width="150" align="center" />
      <el-table-column label="回复信息" prop="feedbackContent" min-width="150" align="center" />
      <el-table-column label="回复时间" prop="feedbackTime" min-width="80" align="center" />
      <el-table-column label="操作" fixed="right" width="80" align="center">
        <template #default="scope">
          <el-button v-show="scope.row.status === 1" link type="warning" size="small"
            v-hasPermi="['business:archiveReceiveTicket:edit']" @click="handleInfo(scope.row)">回复</el-button>
          <span v-if="scope.row.status !== 1">--</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- <Deposit-form ref="DepositRef" :get-list="getList" /> -->
    <el-dialog title="反馈回复" width="500px" v-model="formOpen" append-to-body draggable @close="formCancel">
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="回复信息：">
              <el-input v-if="form.status === 1" v-model.trim="form.feedbackContent" size="small" type="textarea"
                maxlength="200" show-word-limit placeholder="请输入回复信息" :clearable="true" />
              <div v-else>{{ form.feedbackContent }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Finished" size="small" @click="saveHandler">确 定</el-button>
          <el-button icon="close" size="small" @click="formCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
    <!-- 更多搜索弹窗 -->
    <el-dialog title="更多搜索" v-model="moreSearch" width="620px" size="small" append-to-body draggable>
      <el-form :model="queryParams" ref="queryRef" label-width="100">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="反馈月份：" prop="feedbackMonth">
              <el-date-picker v-model="feedbackMonth" size="small" :clearable="true" value-format="YYYY-MM"
                format="YYYY-MM" type="month" />
            </el-form-item>
            <el-form-item label="纳税性质：" prop="taxType">
              <el-select size="small" v-model="queryParams.taxType" placeholder="请选择纳税性质" :clearable="true"
                @change="taxTypeChange">
                <el-option v-for="item in taxTypes" :key="item.label" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源：" prop="fromCompanyName">
              <el-input size="small" v-model="queryParams.fromCompanyName" type="text" placeholder="客户来源"
                :clearable="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Finished" size="small" @click="handleQuery">确 定</el-button>
          <el-button icon="close" size="small" @click="moreSearch = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ReceiveTicketFeedback">
  // import contractForm from "./form";
  import {
    listReceiveTicketFeedback,
    delReceiveTicketFeedback,
    exportReceiveTicketFeedback,
    addReceiveTicketFeedback,
    getReceiveTicketFeedback,
    updateReceiveTicketFeedback,
  } from "@/api/business/production/receiveTicketFeedback";
  import { taxTypes } from "@/utils/default";
  import useUserStore from "@/store/modules/user";
  // import ElImageViewer from 'element-plus/lib/components/image-viewer';
  import { uploadFile } from "@/api/tool/file";
  import { listCompany } from "@/api/business/crm/company";
  import { ref } from "vue";
  // import DepositForm from "./form"
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant;
  const list = ref([]);

  const loading = ref(true);
  const oneself = ref(false);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const moreSearch = ref(false);
  const feedbackMonth = ref(null);
  const total = ref(0);
  const prev = ref([]);
  const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
  const showViewer = ref(false);
  const currentFileList = ref([]);
  const showIndex = ref(0);
  const queryRadio = ref("全部");
  const flag = ref(checkPermission(['business:feedback:person']))
  const flag2 = ref(checkPermission(['business:feedback:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const formOpen = ref(false);

  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 1,
    files: [],
  });

  const emptyForm = {
    id: null,
    companyName: "",
    companyId: null,
    type: 1,
    remark: "",
    files: [],
  };

  const { verify_status } = proxy.useDict("verify_status");
  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    fromCompanyName: "",
    orderByColumn: "create_time",
    companyName: "",
    noContract: 1,
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
  });

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listReceiveTicketFeedback(queryParams.value).then((response) => {
      list.value = response.rows.map((l) => ({ ...l }));
      prev.value = proxy.deepClone(response.rows);
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 是否为自己负责 */
  function handleOneself() {
    if (oneself.value) {
      queryParams.value.principal = useUserStore().user.userId;
    } else {
      queryParams.value.principal = null;
    }
    getList();
  }
  function checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    if (feedbackMonth.value != null) {
      queryParams.value.year = feedbackMonth.value.substr(0, 4);
      queryParams.value.month = feedbackMonth.value.substr(5);
    }
    queryParams.value.pageNum = 1;
    getList();
    moreSearch.value = false;
  }

  /** 重置按钮操作 */
  function resetQuery() {
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      orderByColumn: "create_time",
      companyName: "",
      noContract: 1,
    };
    feedbackMonth.value = null;
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  function formCancel() {
    formOpen.value = false;
    reset();
  }

  function reset() {
    form.value = proxy.deepClone(emptyForm);
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    // const id = row.id || ids.value;
    // proxy.$refs.DepositRef.open(id);
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delReceiveTicketFeedback(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 导出按钮操作 */
  function handleExport() {
    exportReceiveTicketFeedback(queryParams.value);
  }

  function saveHandler() {
    if (form.value.feedbackContent == null || form.value.feedbackContent === "") {
      proxy.$modal.msgError("请输入回复信息");
      return;
    }
    if (form.value.id == null) {
      addReceiveTicketFeedback(form.value).then((res) => {
        formCancel();
        getList();
      });
    } else {
      form.value.status = 2;
      updateReceiveTicketFeedback(form.value).then((res) => {
        formCancel();
        getList();
      });
    }
  }

  function upload(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        form.value.files.push(file);
      }
    });
  }

  function openFollowFile(arg) {
    // console.log(arg)
    const attach = arg;
    window.open(`${arg.url}`, arg.fileName);
  }

  function showFileList(row) {
    currentFileList.value = row.files.map((l) => `${baseUrl.value}${l.fileUrl}`);
    showViewer.value = true;
  }

  function closeImages() {
    showViewer.value = false;
  }

  function handleInfo(row) {
    formOpen.value = true;
    getForm(row.id);
  }

  function getForm(id) {
    getReceiveTicketFeedback(id).then((res) => {
      form.value = res.data;
      if (form.value == null) {
        reset();
      }
    });
  }

  function handleDelFile(index) {
    form.value.files.splice(index, 1);
  }

  function radioChangeHandler(arg) {
    const query = {
      // mainAccountSetsId: store.getters.accountSets.id,
      total: 0,
      pageSize: 20,
      pageNum: 1,
    };
    switch (arg) {
      case "全部":
        query.needSync = null;
        break;
      case "流转反馈":
        // query.isFinished = true
        query.needSync = 0;
        break;
      case "驳回反馈":
        query.needSync = 1;
        break;
      default:
        break;
    }
    queryParams.value = query;
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

  function edit(row) { }

  getList();
</script>