<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:salary:export']">
              导出</el-dropdown-item>
          </el-dropdown-menu>
          <el-dropdown-item icon="Upload" @click="handleImport"
            v-hasPermi="['business:salary:import']">导入</el-dropdown-item>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="客户名称：" prop="companyName">
        <el-input v-model="queryParams.companyName" style="width: 130px" size="small" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户标签：">
        <el-select v-model="queryParams.customerLabelId" style="width:130px" size="small" clearable>
          <el-option v-for="item in options" :key="item.id" :label="item.lable" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份：">
        <el-select v-model.trim="queryParams.month" placeholder="月份" size="small" style="width: 130px"
          :clearable="false" @change="handleQuery">
          <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 label="审核人：" prop="verifierName">
        <el-input size="small" v-model="queryParams.verifierName" placeholder="请输入审核人" clearable style="width: 130px"
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item prop="dateFilter" label="审核时间：">
        <el-date-picker size="small" v-model="queryParams.dateFilter" type="daterange" clearable
          format="YYYY - MM - DD " value-format="YYYY-MM-DD" range-separator="至" start-placeholder="业务日期"
          end-placeholder="业务日期" style="width: 70%;"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:" v-hasPermi="['business:noindividual:person']">
          <el-switch v-model="oneself" @change="handleOneself" />
        </el-form-item> -->
        <el-button type="primary" icon="Search" @click="handleQuery" size="small">搜索</el-button>
        <el-button icon="operation" @click="moreSearch = true" size="small">更多</el-button>
        <el-button icon="Refresh" @click="resetQuery" size="small">重置</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 label="客户名称" align="center" prop="companyName" min-width="250">
        <template #default="scope">
          <div style="display: flex; align-items: center; ">
            <template v-if="scope.row.customerLabelName ">
              <el-tooltip :content="scope.row.customerLabelName" placement="top">
                <el-icon :size="15">
                  <CollectionTag />
                </el-icon>
              </el-tooltip>
              <span style="padding-left:5px;">{{ scope.row.companyName }}</span>
            </template>
            <template v-else>
              <div style="width: 20px; height: 15px;"></div>
              <span>{{ scope.row.companyName }}</span>
            </template>
          </div>
        </template>
      </el-table-column>
      <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="纳税性质" min-width="100" align="center" prop="taxType" />

      <el-table-column label="所属期" min-width="90" align="center">
        <template #default="scope">
          <!-- {{
          scope.row.currentDate != null &&
          scope.row.currentDate > scope.row.checkoutDate
          ? scope.row.currentDate
          : scope.row.checkoutDate
        }} -->
          {{ proxy.moment().subtract(1, "month").format("yyyy")+"-"+queryParams.month}}
        </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-column label="审核人" align="center" prop="verifierName" min-width="100" />
      <el-table-column label="审核时间" align="center" prop="verifierTime" min-width="100" :show-overflow-tooltip="true" />

      <el-table-column label="税号" align="center" prop="socialCreditCode" min-width="150"
        :show-overflow-tooltip="true" />
    </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" />
    <import-excel-dialog ref="importExcelDialogRef" :get-list="getList" />
    <view-dialog ref="viewDialogRef" :get-list="getList" />
    <!-- 更多搜索弹窗 -->
    <el-dialog title="更多搜索" v-model="moreSearch" width="620px" append-to-body draggable>
      <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 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 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="来源：" v-if="tenant.versionId === '4'">
              <el-input size="small" v-model="queryParams.fromCompanyName" type="text" placeholder="客户来源"
                :clearable="true" />
            </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-form-item label="是否有个税：">
              <el-select v-model.trim="queryParams.hasIndividualIncomeTax" placeholder="请选择" size="small"
                style="width: 100%" @change="changeIndividual">
                <el-option v-for="item in confirmChoices" :key="item.value" :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="Salary">
  import useUserStore from "@/store/modules/user";
  import { taxTypes } from "@/utils/default";
  import { listSalary, exportSalary } from "@/api/business/production/salary";
  import { listCompany } from "@/api/business/crm/company";
  import importExcelDialog from "./importExcelDialog.vue";
  import { listLableNoPage } from "@/api/business/lable"
  import { 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 loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const moreSearch = ref(false);
  const oneself = ref(false);
  const multiple = ref(true);
  const importExcelDialogRef = ref(null);
  const total = ref(0);
  const prev = ref([]);
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  const flag = ref(checkPermission(['business:noindividual:person']))
  const flag2 = ref(checkPermission(['business:noindividual:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const options = ref([]);
  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",
      },
    ],
    confirmChoices: [
      {
        label: "是",
        value: 1,
      },
      {
        label: "否",
        value: 0,
      },
    ],
  });

  const { selectStatus, selectMonths, confirmChoices } = toRefs(data);

  const formDialogRef = ref(null);
  const viewDialogRef = ref(null);

  const form = ref({
    id: null,
    companyName: "",

    companyId: null,
    remark: "",
    type: 1,
  });

  const emptyForm = {
    id: null,
    companyName: "",
    companyId: null,
    type: 2,
    remark: "",
    noContract: 1,
  };
  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 getOption() {
    listLableNoPage().then(res => {
      options.value = res.data
    })
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 查询对象 */
  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,
  };

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listSalary(queryParams.value).then((response) => {
      list.value = response.rows;
      total.value = response.total;
      loading.value = false;
      console.log(response.rows);
    });
  }

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

  /** 是否为自己负责 */
  function handleOneself() {
    if (oneself.value) {
      queryParams.value.principal = useUserStore().user.userId;
    } else {
      queryParams.value.principal = null;
    }
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    // proxy.resetForm("queryRef");
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      orderByColumn: "create_time",
      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 === 1 || detail.status === 0 || detail.status == null) {
      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:salary:view")
    );
  }

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

  function verifiable() {
    // console.log(permissions)
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:salary:verify")
    );
  }

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

  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 handleImport() {
    importExcelDialogRef.value.open();
  }

  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",
      };
    }
  }
  queryParams;
  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();
  getOption();
</script>