<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <!-- <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['business:workOrder:remove']">删除</el-button> -->
      <el-dropdown trigger="click">
        <el-button type="primary" size="small" v-if="
            hasPermi([
              'business:customer:service:loop:export',
              'business:customer:service:loop:transactor',
            ])
          ">
          其它<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-if="hasPermi(['business:customer:service:loop:export'])">
              导出</el-dropdown-item>
            <el-dropdown-item icon="Operation" @click="setServiceHandler"
              v-if="hasPermi(['business:customer:service:loop:transactor'])">
              设置执行人</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="68px">
      <el-form-item label="客户名称：" prop="companyName">
        <el-input style="width: 150px" v-model="queryParams.companyName" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="月份：" prop="month">
        <el-select v-model.trim="queryParams.month" size="small" placeholder="月份" :clearable="true" style="width: 130px"
          @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="状态：" prop="status">
        <el-select v-model.trim="queryParams.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>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表区 -->
    <el-table v-loading="loading" :data="serviceList" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名称" align="center" min-width="250" prop="companyName" />
      <el-table-column label="纳税性质" min-width="100" align="center" prop="taxType" />
      <el-table-column label="税号" align="center" prop="socialCreditCode" min-width="180" />
      <el-table-column label="项目" align="center" prop="taskTypeName" min-width="90">
        <template #default="scope">
          {{ scope.row.taskTypeName }}
        </template>
      </el-table-column>
      <el-table-column label="当前期间" width="90" align="center">
        <template #default="scope">
          <!-- {{ scope.row.currentDate != null && scope.row.currentDate > scope.row.checkoutDate ? scope.row.currentDate :
            scope.row.checkoutDate }} -->

          {{
          scope.row.taskTypeId === "1"
          ? moment().subtract(1, "month").format("YYYY年MM月")
          : moment().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="handleByRow(scope.row, item.value)" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="工单执行人" align="center" min-width="100">
        <template #default="scope">{{ getTransactor(scope.row) }}</template>
      </el-table-column>
    </el-table>
    <!-- </div>
    </div> -->
    <!-- <workorder-form ref="workOrderRef" :get-list="getList" /> -->
    <el-dialog title="新增工单" v-model="formOpen" width="500px" append-to-body draggable :close-on-click-modal="false">
      <el-form ref="dictRef" :model="form" label-width="100">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="客户名称" prop="companyName">
              <el-autocomplete :fetch-suggestions="querySearchCompanyAsync" :trigger-on-focus="true"
                v-model="form.companyName" placeholder="请输入客户名称" popper-class="my-autocomplete"
                @select="handleSelectCompany">
                <template #default="{ item }">
                  <div style="
                      display: flex;
                      flex-direction: row;
                      justify-content: space-between;
                    ">
                    <div class="name" style="font-size: 12px">
                      {{ item.name }}
                    </div>
                    <!-- <span class="code" style="font-size: 10px; color: darkgrey;">{{ item.code }}</span> -->
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model.trim="form.remark" type="textarea" width="100%" size="small" placeholder="备注"
                :clearable="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveHandler">确 定</el-button>
          <el-button @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" />
    <service-form ref="serviceRef" :get-list="getList" />
    <housing-fund-form ref="housingFundFormRef" :get-list="getList" />
    <housing-fund-view ref="housingFundViewRef" :get-list="getList" />
    <keep-account-form ref="keepAccountFormRef" :get-list="getList" />
    <keep-account-view ref="keepAccountViewRef" :get-list="getList" />
    <social-security-form ref="socialSecurityFormRef" :get-list="getList" />
    <social-security-view ref="socialSecurityViewRef" :get-list="getList" />
  </div>
</template>

<script setup name="Loop">
  // import contractForm from "./form";
  import auth from "@/plugins/auth";
  import { listLoop, exportLoop } from "@/api/business/crm/serviceWorkOrder";
  import { listCompany } from "@/api/business/crm/company";
  import serviceForm from "../serviceForm";
  import { reactive, ref, toRefs } from "vue";
  import KeepAccountView from "./keepAccountView";
  import KeepAccountForm from "./keepAccountForm";
  import HousingFundForm from "./housingFundForm";
  import HousingFundView from "./housingFundView";
  import SocialSecurityForm from "./socialSecurityForm";
  import SocialSecurityView from "./socialSecurityView.vue";
  import useUserStore from "@/store/modules/user";
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";

  // import workorderForm from "./form"
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const serviceList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const prev = ref([]);
  const keepAccountFormRef = ref(null);
  const keepAccountViewRef = ref(null);
  const socialSecurityFormRef = ref(null);
  const socialSecurityViewRef = ref(null);
  const housingFundFormRef = ref(null);
  const housingFundViewRef = ref(null);

  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: 3,
        color: "#2FCB81",
      },
    ],
  });
  const { selectStatus, selectMonths } = toRefs(data);

  const formOpen = ref(false);

  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: "t1.create_time",
    year: proxy.moment().format("YYYY"),
    companyName: "",
    type: 1,
  });

  const editStatus = {
    startMonth: false,
  };

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

  /** 搜索按钮操作 */
  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;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    // proxy.$refs.workOrderRef.open();
    formOpen.value = true;
  }

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

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

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

  /** 导出按钮操作 */
  function handleExport() {
    if (queryParams.value.month) {
      exportLoop(queryParams.value);
    } else {
      proxy.$modal.msgError("请选择导出月份");
    }
  }

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

  function querySearchCompanyAsync(queryString, cb) {
    const query =
      queryString.length > 0
        ? {
          keyword: queryString,
          pageSize: 20,
          pageNum: 1,
          orderByColumn: "create_time",
        }
        : { pageSize: 20, pageNum: 1, orderByColumn: "create_time" };
    listCompany(query).then((res) => {
      cb(res.rows);
    });
  }

  function handleSelectCompany(item) {
    form.value.companyName = item.name;
    form.value.companyId = item.id;
  }

  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.records.findIndex((v) => v.month === month);
    if (index >= 0) {
      return {
        backgroundColor: getStatusColor(row.records[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;
  }

  function setServiceHandler() {
    if (ids.value.length === 0) {
      proxy.$modal.msgError("请先选择需要设置的工单！");
      return;
    }
    proxy.$refs["serviceRef"].open({
      dialogTitle: "设置执行人",
      dialogContent: "请输入执行人姓名",
      values: ids.value,
    });
  }

  function getTransactor(row) {
    if (row.entrusts != null && row.entrusts.length > 0) {
      const names = Array.from(new Set(row.entrusts.map((v) => v.toAccountName)));
      return names.join(",");
    } else {
      return row.serviceName;
    }
  }

  function handleByRow(row, item) {
    console.log(row);
    const record = row.records.find(
      (v) =>
        v.fromId === "0" && v.year === queryParams.value.year && v.month === item
    );
    const editable =
      permissions.includes(all_permission) ||
      permissions.includes("business:customer:service:loop:edit") >= 0;
    const viewable =
      permissions.includes(all_permission) ||
      permissions.includes("business:customer:service:loop:view") >= 0;
    // if (record == null && row.isStop == 1) {
    //   proxy.$modal.msg("工单已终止");
    //   return;
    // }
    if (
        row.entrusts != null &&
        row.entrusts.length > 0 &&
        (editable || viewable)
    ) {
      if (
          row.entrusts.findIndex(
              proxy.moment(v.currentMonth).format("YYYYMM") ===
              queryParams.value.year + item
          ) >= 0
      ) {
        if (row.taskTypeId === "1") {
          keepAccountViewRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "2") {
          socialSecurityViewRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "3") {
          housingFundViewRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "4") {
        }
      } else if (editable) {
        if (row.taskTypeId === "1") {
          keepAccountFormRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "2") {
          socialSecurityFormRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "3") {
          housingFundFormRef.value.open({
            workOrderId: row.id,
            month: item,
            year: queryParams.value.year,
            companyId: row.companyId,
            companyName: row.companyName,
          });
        } else if (row.taskTypeId === "4") {
        }
      } else {
        proxy.$modal.msg("没有修改权限");
      }
    } else if (editable) {
      if (row.taskTypeId === "1") {
        keepAccountFormRef.value.open({
          workOrderId: row.id,
          month: item,
          year: queryParams.value.year,
          companyId: row.companyId,
          companyName: row.companyName,
        });
      } else if (row.taskTypeId === "2") {
        socialSecurityFormRef.value.open({
          workOrderId: row.id,
          month: item,
          year: queryParams.value.year,
          companyId: row.companyId,
          companyName: row.companyName,
        });
      } else if (row.taskTypeId === "3") {
        housingFundFormRef.value.open({
          workOrderId: row.id,
          month: item,
          year: queryParams.value.year,
          companyId: row.companyId,
          companyName: row.companyName,
        });
      } else if (row.taskTypeId === "4") {
      }
    } else {
      proxy.$modal.msg("没有修改权限");
    }
  }

  function hasPermi(arr) {
    return auth.hasPermiOr(arr);
  }
  getList();
</script>