<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-if="viewAdviser('business:workOrder:export')">
              导出</el-dropdown-item>
            <el-dropdown-item icon="Edit" @click="handleSetContinue" v-if="viewAdviser('business:workOrder:continue')">
              延续设置</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 v-model="queryParams.companyName" style="width: 150px" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型：" prop="type">
        <el-select size="small" v-model="queryParams.type" placeholder="工单类型" clearable>
          <el-option v-for="item in types" :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="orderList" 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" :resizable="false" />
      <el-table-column label="税号" align="center" min-width="200" prop="socialCreditCode" :resizable="false" />
      <el-table-column label="工单类型" align="center" prop="amount" min-width="80" :resizable="false">
        <template #default="scope">
          {{ scope.row.type === 1 ? "循环工单" : "代办工单" }}
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" prop="taskTypeName" :resizable="false" min-width="110">
        <template #default="scope">
          {{ scope.row.taskTypeName }}
          {{
          scope.row.taskTypeDetailName
          ? `-${scope.row.taskTypeDetailName}`
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="是否延续" align="center" prop="isContinue" :resizable="false">
        <template #default="scope">
          {{ scope.row.isContinue === 0 ? "否" : "是" }}
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" width="150" prop="socialCreditCode" :resizable="false">
        <template #default="scope">
          <span v-if="scope.row.type === 1">{{ scope.row.closingMonth }}</span>
          <span v-else>{{ scope.row.onceContractStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="起始月" align="center" min-width="120" prop="startMonth" :resizable="false">
        <template #default="scope">
          <div v-if="scope.row.type === 1">
            <div v-if="scope.row.editStatus.startMonth" style="
                display: flex;
                flex-direction: row;
                justify-content: center;
              ">
              <el-date-picker v-model="scope.row.startMonth" size="small" placeholder="起始月" :clearable="true"
                value-format="YYYY-MM-DD" format="YYYY年MM月" type="month"
                @change="(arg) => startDateChangeHandler(scope.row, arg)" />
              <el-button link type="primary" icon="Check" size="small" style="padding: 0"
                @click="saveHandler(scope.row, 'startMonth')" />
            </div>
            <div v-else style="
                display: flex;
                flex-direction: row;
                justify-content: center;
              ">
              <div style="width: auto">
                {{
                scope.row.startMonth
                ? moment(scope.row.startMonth).format("YYYY年MM月")
                : ""
                }}
              </div>
              <el-button v-show="
                  scope.row.isStop === 0 && scope.row.records.length === 0
                " link type="primary" icon="Edit" size="small" style="padding: 0"
                v-hasPermi="['business:workOrder:edit']" @click="
                  () => {
                    scope.row.editStatus.startMonth =
                      !scope.row.editStatus.startMonth;
                  }
                " />
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="结束月" align="center" min-width="90" :resizable="false">
        <template #default="scope">
          <div v-if="scope.row.monthNum > 0">
            {{
            scope.row.type === 1
            ? scope.row.endMonth
            ? moment(scope.row.endMonth).format("YYYY年MM月")
            : ""
            : "-"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="工单月数" align="center" :resizable="false" width="80" prop="monthNum">
        <template #default="scope">
          {{ scope.row.type === 1 ? scope.row.monthNum : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="工单执行人" align="center" :resizable="false" min-width="100">
        <template #default="scope">{{ getTransactor(scope.row) }}</template>
      </el-table-column>
    </el-table>
    <!-- <contract-form ref="contractRef" :get-list="getList" /> -->
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <ZeroChangeDialog ref="zeroChangeDialogRef" :save-call-back="thenSave" />
    <el-dialog title="延续设置" v-model="continueOpen" width="500px" append-to-body draggable @close="close"
      :close-on-click-modal="false">
      <div style="padding: 8px 24px 16px 24px">
        <el-form size="small" label-width="100px">
          <el-form-item label="是否延续">
            <el-select v-model="cont" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in yesOrNo" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-btns-container" style="height: 40px">
        <el-button size="small" style="float: right" @click="close" icon="close">
          取消</el-button>
        <el-button type="primary" icon="Finished" size="small"
          style="float: right; margin-left: 12px; margin-right: 12px" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="ContractWorkOrder">
  import {
    listWorkOrder,
    delWorkOrder,
    exportWorkOrder,
    updateWorkOrder,
    setContract,
  } from "@/api/business/crm/workOrder";
  import useUserStore from "@/store/modules/user";
  import { yesOrNo } from "@/utils/default";
  import { get } from "@vueuse/core";
  import { ref } from "vue";
  import ZeroChangeDialog from "../ZeroChangeDialog";
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const orderList = ref([]);
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  const continueOpen = ref(false);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const cont = ref(1);
  const setContinue = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const prev = ref([]);
  const zeroChangeDialogRef = ref(null);

  const { contract_verify_status } = proxy.useDict("contract_verify_status");
  const { contract_status } = proxy.useDict("contract_status");
  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    companyName: "",
    orderByColumn: "create_time",
    noContract: 0,
  });

  const types = ref([
    {
      value: 1,
      label: "循环工单",
    },
    {
      value: 2,
      label: "代办工单",
    },
  ]);

  const editStatus = {
    startMonth: false,
  };

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listWorkOrder(queryParams.value).then((response) => {
      orderList.value = response.rows.map((l) => ({
        ...l,
        editStatus: proxy.deepClone(editStatus),
      }));
      prev.value = proxy.deepClone(response.rows);
      total.value = response.total;
      loading.value = false;
      console.log("查询", orderList);
    });
  }

  /** 搜索按钮操作 */
  function handleSetContinue() {
    if (ids.value.length < 1) {
      proxy.$modal.msgError("至少选择一条数据");
    } else {
      if (setContinue) {
        proxy.$modal.msgError("只能修改循环工单");
      } else {
        continueOpen.value = true;
      }
    }
  }

  /** 延续设置保存操作 */
  function handleSave() {
    setContract(ids.value, cont.value).then((response) => {
      proxy.$modal.msgSuccess("保存成功");
      continueOpen.value = false;
      getList();
    });
  }

  //判断是否有权限
  function viewAdviser(quer) {
    return permissions.includes(all_permission) || permissions.includes(quer);
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  function close() {
    continueOpen.value = false;
    cont.value = 1;
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    setContinue.value = selection.map((item) => item.type === 2);
  }

  /** 新增按钮操作 */
  function handleAdd() {
    proxy.$refs.contractRef.open();
  }

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

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

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

  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 saveHandler(row, field) {
    const index = prev.value.findIndex((l) => l.id === row.id);
    if (prev.value[index][field] === row[field]) {
      row.editStatus[field] = !row.editStatus[field];
    } else {
      if (row.isZero == null) {
        zeroChangeDialogRef.value.open(row.companyId, row);
      } else {
        proxy.$modal
          .confirm("确定修改起始月么?")
          .then((_) => {
            updateWorkOrder(row).then((res) => {
              getList();
            });
          })
          .catch((_) => { });
      }
    }
  }

  function thenSave(row) {
    proxy.$modal
      .confirm("确定修改起始月么?")
      .then((_) => {
        updateWorkOrder(row).then((res) => {
          getList();
        });
      })
      .catch((_) => { });
  }

  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;
    }
  }
  getList();
</script>