<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:production:onceexport']">
              导出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- v-hasPermi="['business:entrust:workOrder:current:export']"> -->
    <!-- 搜索区 -->
    <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" style="width: 150px" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单状态：" prop="recordStatus">
        <el-select v-model="queryParams.recordStatus" placeholder="请选择工单状态" clearable @change="handleQuery">
          <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="handlerName">
        <el-input v-model="queryParams.handlerName" style="width: 150px" placeholder="请输入领取人" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目：" prop="taskTypeName">
        <el-input v-model="queryParams.taskTypeName" style="width: 150px" placeholder="请输入项目" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item v-if="tenant.versionId !== '4'" label="是否自己负责:" v-hasPermi="['business:once: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="Refresh" @click="resetQuery">重置</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="workOrderNo" width="200" /> -->
      <el-table-column label="客户名称" align="center" min-width="250" prop="companyName" />
      <!-- <el-table-column
        label="税号"
        align="center"
        prop="socialCreditCode"
        min-width="150"
      /> -->
      <el-table-column label="来源" align="center" prop="accountName" min-width="150" v-if="tenant.versionId == '4'" />
      <!-- <el-table-column label="工单类型" align="center" prop="amount" width="80">
        <template #default="scope">
          {{ scope.row.type === 1 ? "循环工单" : "代办工单" }}
        </template>
      </el-table-column> -->
      <el-table-column label="项目" align="center" width="200" :show-overflow-tooltip="true">
        <template #default="scope">
          {{
          scope.row.noContract === 1? scope.row.remark: `${scope.row.taskTypeName}${scope.row.alterType
          ?`-${scope.row.alterType}` : ""}${scope.row.taskTypeDetailName? `-${scope.row.taskTypeDetailName}` : ""}`
          }}
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="explain" min-width="180" />
      <el-table-column label="委托时间" align="center" min-width="140">
        <template #default="scope">
          {{
          scope.row.record != undefined
          ? scope.row.record.entrustTime
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="执行人" align="center" width="100" :show-overflow-tooltip="true">
        <template #default="scope">
          {{
          scope.row.entrust != null
          ? scope.row.entrust.toAccountName
          : scope.row.serviceName
          }}
        </template>
      </el-table-column>
      <el-table-column label="领取人" align="center" min-width="100" :show-overflow-tooltip="true">
        <template #default="scope">
          {{
          scope.row.record != undefined
          ? scope.row.record.handlerName
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" min-width="140">
        <template #default="scope">
          {{
          scope.row.record != undefined
          ? scope.row.record.handlerTime
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="完成人" align="center" min-width="100">
        <template #default="scope">
          {{
          scope.row.record != undefined
          ? scope.row.record.recorderName
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" min-width="140">
        <template #default="scope">
          {{
          scope.row.record != undefined
          ? scope.row.record.finishTime
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <div :style="getStatusStyle(scope.row)">
            {{ getStatusLabel(scope.row) }}
            <el-popover placement="top-start" width="250" trigger="hover">
              <div style="display: flex; flex-direction: row">
                <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;
                      font-size: 10px;
                    ">
                    {{ item.label }}
                  </div>
                </div>
              </div>
              <template #reference>
                <span style="
                    color: #fff;
                    font-size: 12px;
                    text-align: center;
                    display: inline-block;
                    line-height: 14px;
                    width: 14px;
                    height: 14px;
                    background-color: #ccc;
                    border-radius: 50%;
                  ">?</span>
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="130" align="center" prop="">
        <template #default="scope">

          <el-button v-if="scope.row.record != null && scope.row.record.status == 1" size="small" type="primary" link
            v-hasPermi="['business:production:onceWork:finished']" @click="finishedHandle(scope.row)">
            完成
          </el-button>
          <el-button v-if="scope.row.record == null || scope.row.record.status == 0" size="small" type="primary" link
            v-hasPermi="['business:production:onceWork:finished']" @click="finishedHandle2(scope.row)">
            领取
          </el-button>

          <el-button
            v-if="scope.row.record !== undefined && scope.row.record.status == 1 && scope.row.record.handlerId  ===  useUserStore().user.userId"
            size="small" type="primary" link v-hasPermi="['business:production:onceWork:finished']"
            @click="finishedHandle3(scope.row)">
            取消领取
          </el-button>
        </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" />
  </div>
</template>

<script setup name="OnceWork">


  import {
    listOnceWorkOrder,
    saveDetail,
    exportOnceWork, receive
  } from "@/api/business/production/onceWorkOrder";
  import { toRefs } from "vue";
  import useUserStore from "@/store/modules/user";
  const { proxy } = getCurrentInstance();

  const data = reactive({
    selectStatus: [
      {
        label: "未开始",
        value: 0,
        color: "#888",
      },
      {
        label: "办理中",
        value: 1,
        color: "#FFB836",
      },
      {
        label: "已完成",
        value: 3,
        color: "#2FCB81",
      },


    ],
  });

  const { selectStatus } = toRefs(data);

  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant;
  const list = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const selections = ref([]);
  const oneself = ref(false);
  const single = ref(false);
  const multiple = ref(false);
  const total = ref(0);
  const prev = ref([]);
  const flag = ref(checkPermission(['business:once:person']))
  const flag2 = ref(checkPermission(['business:once:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const setEntrustDialogRef = 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,
    orderByColumn: "create_time",
    companyName: "",
    type: 2,
    principal: !flag.value ? useUserStore().user.userId : null,
  });

  const editStatus = {
    startMonth: false,
  };

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listOnceWorkOrder(queryParams.value).then((response) => {
      list.value = 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 checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    console.log(activeName);
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    selections.value = selection;
    single.value = selection.length != 1;
    multiple.value = selection.length > 0;
  }

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

  function getStatusStyle(row) {
    if (row.record == null) {
      return { color: getStatusColor(0), verticalAlign: "middle" };
    } else {
      return {
        color: getStatusColor(row.record.status),
        verticalAlign: "middle",
      };
    }
  }
  function getStatusColor(status) {
    const index = selectStatus.value.findIndex((v) => v.value === status);
    return index >= 0 ? selectStatus.value[index].color : "#fff";
  }
  function getStatusLabel(row) {
    const index = selectStatus.value.findIndex(
      (v) => v.value === (row.record == null ? 0 : row.record.status)
    );
    return index >= 0 ? selectStatus.value[index].label : "";
  }

  function finishedHandle(row) {
    proxy.$modal
      .confirm("确认完成工单么?")
      .then((_) => {

        const finishedValue =
          row.record != null
            ? row.record
            : {
              companyId: row.companyId,
              workOrderId: row.id,
              tenantId: row.tenantId,
              status: 3,
            };


        loading.value = true
        saveDetail(finishedValue).then((res) => getList());
      })
      .catch((_) => {
        proxy.$modal.msgError("取消完成工单");
      }).finally(() => loading.value = false);

  }
  function finishedHandle2(row) {
    proxy.$modal
      .confirm("确认领取工单么?")
      .then((_) => {
        console.log(row);
        const finishedValue =
          row.record != null
            ? row.record
            : {
              companyId: row.companyId,
              workOrderId: row.id,
              tenantId: row.tenantId,
              status: 1,
            };
        loading.value = true
        receive(finishedValue).then((res) => getList());
      })
      .catch((_) => {
        proxy.$modal.msgError("取消领取工单");
      }).finally(() => loading.value = false);
  }

  function finishedHandle3(row) {
    proxy.$modal
      .confirm("确认取消领取么?")
      .then((_) => {
        console.log(row);
        const finishedValue =
          row.record != null
            ? row.record
            : {
              companyId: row.companyId,
              workOrderId: row.id,
              tenantId: row.tenantId,
              status: 0,
            };
        loading.value = true
        receive(finishedValue).then((res) => getList());
      })
      .catch((_) => {
        proxy.$modal.msgError("取消领取工单");
      }).finally(() => loading.value = false);
  }
  getList();
</script>