<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:salaryZero:export']">
              导出</el-dropdown-item>
            <el-dropdown-item icon="Upload" @click="handleImport"
              v-hasPermi="['business:salaryZero:import']">导入</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="78px">
      <el-form-item label="客户名称：" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入客户名称" clearable style="width: 150px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="月份：">
        <el-select v-model.trim="queryParams.month" size="small" placeholder="月份" style="width: 130px"
          @change="handleQuery" :clearable="false">
          <el-option v-for="item in selectMonths" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model.trim="queryParams.status" prop="status" size="small" type="text" placeholder="状态"
          :clearable="true" style="width: 130px" @clear="clearStatus">
          <el-option v-for="item in selectStatus" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:"  v-hasPermi="['business:wage: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>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" v-if="flag">
      <el-tab-pane label="全部" name="first">
     
      </el-tab-pane>

      <el-tab-pane label="我的" name="second">
     
         
      </el-tab-pane>
    </el-tabs>
    <!-- 列表区 -->
    <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 label="客户名称" align="center" prop="companyName" min-width="250" />
      <el-table-column label="来源" align="center" prop="fromCompanyName" min-width="100" />
      <el-table-column label="纳税性质" align="center" min-width="130" prop="taxType" />
      <el-table-column label="税号" align="center" prop="socialCreditCode" min-width="200" />
      <el-table-column label="当前期间" min-width="90" align="center">
        <template #default="scope">
          {{ moment().subtract(1, "month").format("YYYY年MM月") }}
        </template>
      </el-table-column>
      <el-table-column align="center">
        <template #header>
          <div style="
           display: flex;
           flex-direction: row;
           justify-content: space-between;
         ">
            <div style="display: flex; flex-direction: row">
              <el-button link type="primary" size="small" icon="ArrowLeft" @click="prevYear" />
              <el-link style="margin: 0 40px" :underline="false">{{
                queryParams.year
                }}</el-link>
              <el-button link type="primary" icon="ArrowRight" size="small" @click="nextYear" />
            </div>
            <div style="display: flex; flex-direction: row; margin-right: 20px">
              <div v-for="item in selectStatus" :key="item.value"
                style="display: flex; flex-direction: row; margin-right: 10px">
                <div :style="{
                 backgroundColor: item.color,
                 width: '14px',
                 height: '14px',
                 margin: 'auto',
                 borderRadius: '50%',
                 border: item.color === '#fff' ? '1px solid #ddd' : 'none',
               }" />
                <div style="
                 display: inline-block;
                 margin-left: 10px;
                 line-height: 36px;
               ">
                  {{ item.label }}
                </div>
              </div>
            </div>
          </div>
        </template>
        <el-table-column v-for="item in selectMonths" :key="item.value" min-width="50" :label="item.label"
          align="center">
          <template #default="scope">
            <el-button size="small" :style="monthStatusStyle(scope.row, item.value)" circle
              @click="openDetail(scope.row, item)" style="width: 12px; height: 12px" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="执行人" align="center" prop="serviceName" min-width="100">
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <form-dialog ref="formDialogRef" :get-list="getList" @getList = "getList"/>/>
    <view-dialog ref="viewDialogRef" :get-list="getList" />
    <import-excel-dialog ref="importExcelDialogRef" :get-list="getList" />
    <!-- 更多搜索弹窗 -->
    <el-dialog title="更多搜索" v-model="moreSearch" width="620px" append-to-body draggable :close-on-click-modal = "false">
      <el-form :model="queryParams" ref="queryRef" size="small" label-width="100">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称：" prop="companyName">
              <el-input v-model="queryParams.companyName" size="small" placeholder="请输入客户名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item v-if="tenant.versionId === '4'" label="来源：">
              <el-input size="small" v-model="queryParams.fromCompanyName" type="text" placeholder="客户来源"
                :clearable="true" />
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model.trim="queryParams.status" prop="status" size="small" type="text" placeholder="状态"
                :clearable="true" @clear="clearStatus">
                <el-option v-for="item in selectStatus" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月份：">
              <el-select v-model.trim="queryParams.month" size="small" placeholder="月份" @change="handleQuery"
                :clearable="false">
                <el-option v-for="item in selectMonths" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="纳税性质：">
              <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-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="Company">
  import useUserStore from "@/store/modules/user";
  import { taxTypes } from "@/utils/default";
  import { listSalary, exportSalary } from "@/api/business/production/salaryZero";
  import { listCompany } from "@/api/business/crm/company";
  import importExcelDialog from "./importExcelDialog.vue";
  import { compile, reactive, ref, toRefs } from "vue";

  import formDialog from "./form";
  import viewDialog from "./view";
  // import workorderForm from "./form"
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant;
  const list = ref([]);
  const oneself = ref(false);
  const importExcelDialogRef = ref(null);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const moreSearch = ref(false);
  const total = ref(0);
  const prev = ref([]);
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";

  const data = reactive({
    selectMonths: [
      {
        label: "一月",
        value: "01",
      },
      {
        label: "二月",
        value: "02",
      },
      {
        label: "三月",
        value: "03",
      },
      {
        label: "四月",
        value: "04",
      },
      {
        label: "五月",
        value: "05",
      },
      {
        label: "六月",
        value: "06",
      },
      {
        label: "七月",
        value: "07",
      },
      {
        label: "八月",
        value: "08",
      },
      {
        label: "九月",
        value: "09",
      },
      {
        label: "十月",
        value: "10",
      },
      {
        label: "十一月",
        value: "11",
      },
      {
        label: "十二月",
        value: "12",
      },
    ],
    selectStatus: [
      {
        label: "未开始",
        value: 0,
        color: "#fff",
      },
      {
        label: "待确认",
        value: 1,
        color: "#ffb836",
      },
      {
        label: "待审核",
        value: 2,
        color: "#0F8BFF",
      },
      {
        label: "已完成",
        value: 3,
        color: "#2FCB81",
      },
      {
        label: "驳回待处理",
        value: 4,
        color: "#E63E3E",
      },
    ],
  });
  const { selectStatus, selectMonths } = toRefs(data);
  const flag = ref(checkPermission(['business:wage:person']))
  const formDialogRef = ref(null);
  const viewDialogRef = ref(null);
  const activeName = flag.value ? ref('first') : ref('second');
  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 1,
  });

  const emptyForm = {
    id: null,
    companyName: "",
    companyId: null,
    type: 2,
    remark: "",
    noContract: 1,
  };

  /** 查询对象 */
  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"),
    companyName: "",
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
  });

  const editStatus = {
    startMonth: false,
  };

  /***********************  方法区  ****************************/

  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listSalary(queryParams.value).then((response) => {
      list.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 是否为自己负责 */
  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 handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
    moreSearch.value = false;
  }

  /** 重置按钮操作 */
  function resetQuery() {
    // proxy.resetForm("queryRef");
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      year: proxy.moment().subtract(1, "month").format("yyyy"),
      month: proxy.moment().subtract(1, "month").format("MM"),
      companyName: "",
    };
    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 reset() {
    form.value = proxy.deepClone(emptyForm);
  }

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

  function openDetail(row, month) {
    // 判断选中月的状态
    const index = row.details.findIndex((l) => l.month == month.value);
    if (index >= 0) {
      const detail = row.details[index];
      directDialog(detail);
    } else {
      const detail = {
        financialSalaryId: row.id,
        companyId: row.companyId,
        companyName: row.companyName,
        month: month.value,
        year: queryParams.value.year,
      };
      directDialog(detail);
    }
  }

  function directDialog(detail) {
    // 判断是否有权限
    if (detail.status === 0 || detail.status == null || detail.status === 1) {
      if (editable()) {
        formDialogRef.value.open(detail);
      } else {
        proxy.$modal.msgError("没有权限");
      }
    } else if (detail.status === 4) {
      if (editable()) {
        formDialogRef.value.open(detail);
      } else if (viewable() || verifiable()) {
        viewDialogRef.value.open(detail);
      } else {
        proxy.$modal.msgError("没有权限");
      }
    } else if (detail.status === 2 || detail.status === 3) {
      if (editable() || viewable() || verifiable()) {
        viewDialogRef.value.open(detail);
      } else {
        proxy.$modal.msgError("没有权限");
      }
    }
  }

  function viewable() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:salaryZero:view")
    );
  }

  function editable() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:salaryZero:edit")
    );
  }

  function verifiable() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:salaryZero:verify")
    );
  }

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

  //导入按钮操作
  function handleImport() {
    importExcelDialogRef.value.open();
  }

  function startDateChangeHandler(row, startDate) {
    if (startDate) {
      // console.log(startDate)
      row.endMonth = proxy
        .moment(startDate)
        .add(row.monthNum - 1, "M")
        .format("YYYY-MM-DD");
    } else row.endMonth = null;
    // console.log(row)
  }

  function prevYear() {
    let currentYear = queryParams.value.year;
    currentYear = Number(currentYear) - 1;
    queryParams.value.year = currentYear.toString();
    handleQuery();
  }

  function nextYear() {
    let currentYear = queryParams.value.year;
    currentYear = Number(currentYear) + 1;
    queryParams.value.year = currentYear.toString();
    handleQuery();
  }

  function monthStatusStyle(row, month) {
    const index = row.details.findIndex((v) => v.month === month);
    if (index >= 0) {
      return {
        backgroundColor: getStatusColor(row.details[index].status),
        verticalAlign: "middle",
        width: "14px",
        height: "14px",
      };
    } else {
      return {
        backgroundColor: getStatusColor(0),
        verticalAlign: "middle",
        width: "14px",
        height: "14px",
      };
    }
  }

  function getStatusColor(status) {
    const index = selectStatus.value.findIndex((v) => v.value === status);
    return index >= 0 ? selectStatus.value[index].color : "#fff";
  }

  function clearStatus() {
    queryParams.value.status = null;
  }

  getList();
</script>