<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" size="small" :inline="true">
      <el-form-item label="客户名称：" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入客户名称" style="width: 150px" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="税号：" prop="socialCreditCode">
          <el-input v-model="queryParams.socialCreditCode" style="width: 150px" placeholder="请输入税号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户负责人：" prop="leaderName">
          <el-input v-model="queryParams.leaderName" placeholder="请输入客户负责人" style="width: 150px" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- <el-form-item v-if="tenant.versionId == '4'" label="来源：" prop="tenantId">
          <el-select v-model="queryParams.tenantId" clearable>
                  <el-option v-for="item in tenantList" :key="item.fromTenantId" :label="item.contactCompany"
                    :value="item.fromTenantId" />
                </el-select>
        </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" size="small">搜索</el-button>
        <!-- <el-button type="primary" icon="Upload" @click="uploadHandle" size="small" v-hasPermi="['business:upload:add']">上传</el-button>
        <el-button type="danger" :disabled="!ids.length" icon="Delete" @click="handleDelete" size="small" v-hasPermi="['business:upload:del']">作废</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" :selectable="selectable" width="55" align="center" /> -->
      <el-table-column label="客户名称" prop="name" min-width="210" align="center" >
        <template #default="scope">
          <div style="display: flex; align-items: center; ">
            <template v-if="scope.row.name ">
              <span style="padding-left:5px;">{{ scope.row.name }}</span>
            </template>
            <template v-else>
              <div style="width: 20px; height: 15px;"></div>
              <span>{{ scope.row.name }}</span>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="税号" min-width="200" align="center" prop="socialCreditCode" />
      <el-table-column label="纳税类型" align="center" min-width="120" prop="taxType" />
      <!-- <el-table-column v-if="tenant.versionId == '4'" label="来源" align="center" min-width="110" prop="tenantId">
        <template #default="scope">
          {{ getTenantName(scope.row) }}
        </template>
      </el-table-column> -->
      <el-table-column label="客服" align="center" min-width="110" prop="adviserName" />
      <el-table-column label="负责人" align="center" min-width="110" prop="leaderName" />
      <el-table-column label="操作" width="130" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link size="small" type="primary" circle
            @click="viewHandle(scope.row)">查看</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-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
    <form-dialog ref="formDialogRef" :getList="getList" :fileTypes="fileTypes" />
    <view-dialog ref="viewDialogRef" :getList="getList" />
    <detail-dialog ref="detailDialogRef" :getList="getList" />
  </div>
</template>

<script setup name="ResouceUpload">
  import { listFile, delFile } from "@/api/business/fileUpload";
  import { downloadFile } from "@/api/tool/file";
  import useUserStore from "@/store/modules/user";
  import { ref, computed } from "vue";
  import formDialog from "./form.vue";
  import viewDialog from "./view.vue";
  import detailDialog from "./detail2.vue";
  import {
    listEntrustOrder,
    listTenant
  } from "@/api/business/entrust/entrustOrder";
  import {
    listProductionCompany,
  } from "@/api/business/production/productionCompany";

  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant
  const list = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const oneself = ref(false);
  const total = ref(0);
  const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
  const showViewer = ref(false);
  const currentFileList = ref([]);
  const showIndex = ref(0);
  const tenantList = ref([]);

  const permissions = useUserStore().permissions;

  const fileTypes = ref([
    {value: 1, label: '票据'},
    {value: 2, label: '银行'},
    {value: 3, label: '社保及公积金'},
    {value: 4, label: '库存表'},
  ])
  const formOpen = ref(false);
  const formDialogRef = ref(null);
  const viewDialogRef = ref(null);
  const detailDialogRef = ref(null);
  const flag = ref(checkPermission(['business:upload:person']))
  const flag2 = ref(checkPermission(['business:upload:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const options = ref([]);
  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 1,
    files: [],
  });

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

  // const getTenantName = computed(() => {
  //   return row => {
  //     const tenant = tenantList.value.find(t => t.fromTenantId == row.tenantId)
  //     if(tenant) {
  //       return tenant.contactCompany
  //     }
  //     return ''
  //   }
  // })

  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time",
    year: proxy.moment().subtract(1, "month").format("yyyy"),
    month: proxy.moment().subtract(1, "month").format("MM"),
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
    tenantVersionId: tenant.versionId,
    isZero: 0,
    deleted: 2
  });

  /***********************  方法区  ****************************/
    /** 查询company列表 */
  function getList() {
    loading.value = true;
    listProductionCompany(queryParams.value).then((response) => {
      list.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  function selectable(row) {
    return !row.deleted
  }

  // function getEntrustOrderList() {
  //   if(tenant.versionId != '4') {
  //     return
  //   }
  //   listEntrustOrder({
  //   pageNum: 1,
  //   pageSize: 999,
  //   status: 1}).then(res => {
  //     tenantList.value = res.rows
  //   })
  // }

 

  onActivated(() => {

  });
  /** 查询company列表 */
  // function getList() {
  //   loading.value = true;
  //   listFile(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 handleQuery() {
    queryParams.value.pageNum = 1;
    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 resetQuery() {
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      year: proxy.moment().format("YYYY"),
      month: proxy.moment().format("MM"),
      orderByColumn: "create_time",
      tenantVersionId: tenant.versionId
    };
    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 handleAdd() {
    // proxy.$refs.DepositRef.open();
    formOpen.value = true;
  }

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

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

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

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


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

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

  function showFeedbackDialog(row) {
    const value = proxy.deepClone(row);
    value.status = 4;
    proxy.$refs.feedbackDialogRef.open(value);
  }

  function verifyDeduction(value) {
    saveDeduction(value).then((res) => {
      getList();
    });
  }

  function currentMonthChange(arg) {
    const year = proxy.moment(arg).format("YYYY");
    const month = proxy.moment(arg).format("MM");
    queryParams.value.year = year;
    queryParams.value.month = month;
    handleQuery();
  }

  function disabledDateHandler(date) {
    if (date <= proxy.moment().subtract(1, "month")) {
      return false;
    } else {
      return true;
    }
  }

  function uploadHandle(row) {
    formDialogRef.value.open();
  }
  function viewHandle(row) {
    console.log(detailDialogRef)
    console.log(detailDialogRef.value)
    console.log(proxy.$refs.detailDialogRef)
    // proxy.$router.push({path: '/Production/detail', query: {companyId: row.id, companyName: row.name}})
    detailDialogRef.value.open({companyId: row.id, companyName: row.name});
  }
  function downloadHandle(row) {
    downloadFile({fileName: row.fileUrl, delete: false})
      .then((blob) => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        // 下载文件的名称及文件类型后缀
        link.download = row.fileName;
        document.body.appendChild(link);
        link.click();
        //在资源下载完成后 清除 占用的缓存资源
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      });
  }
  getList();
  // getTenantList()
  // getEntrustOrderList()
</script>