<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">

    <div class="listbutton">
      <div>
        <el-button type="primary" size="small"
                   icon="Download" @click="handleExport"
                   v-hasPermi="['business:upgrade:workOrder:export']">导出
        </el-button>
      <el-button type="primary" size="small"
                 @click="OrderDisableForm"
                 v-hasPermi="['business:upgrade:workOrder:edit']">停用
      </el-button>
      </div>
        <el-button type="primary" size="small"
                   v-loading.fullscreen.lock="fullscreenLoading"
                   icon="Plus" @click="Upgrade"
                   v-hasPermi="['business:upgrade:workOrder:edit']">完成升级
        </el-button>
      </div>

    </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" placeholder="请输入客户名称" style="width: 150px" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="停用状态：" prop="isStop">
        <el-select
            size="small"
            v-model="queryParams.isStop"
            placeholder="停用状态"
            clearable
            style="width: 90px"
        >
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" selected :value="0"></el-option>
        </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" prop="id" min-width="250" />
      <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">
          {{ scope.row.isStop === 0 ? "否" : "是" }}
        </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  && scope.row.isNew === 1
                " link type="primary" icon="Edit" size="small" style="padding: 0"
                         v-hasPermi="['business:upgrade: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>
    <el-dialog title="新增工单" v-model="formOpen" width="500px" append-to-body draggable>
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="客户名称：" prop="companyName">
              <el-autocomplete style="width: 100%" fit-input-width="300px" size="small"
                :fetch-suggestions="querySearchCompanyAsync" :trigger-on-focus="true" v-model="form.companyName"
                placeholder="请输入客户名称" @select="handleSelectCompany">
                <template #append>
                  <el-button icon="Plus" @click="showAddCompanyDialog">
                  </el-button>
                </template>
                <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-form-item label="服务内容：">
              <el-input v-model.trim="form.remark" type="textarea" size="small" :rows="4" maxlength="200"
                show-word-limit placeholder="服务内容" :clearable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="24"> </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Finished" size="small" @click="saveHandler">确 定</el-button>
          <el-button @click="formCancel" icon="close" size="small">取 消</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" />
    <AddCompanyDialog ref="addCompanyDialogRef" />
  </div>
</template>

<script setup name="WorkOrder">
  // import contractForm from "./form";
  import {
    listWorkOrder,
    delWorkOrder,
    exportWorkOrder,
    addWorkOrder,
    exportNoContract,
    completeUpgrade,
    checkWorkOrder,
    OrderDisable
  } from "@/api/upgrade/workOrder";
  import { listCompany } from "@/api/business/crm/company";
  import AddCompanyDialog from "../AddCompanyDialog.vue";
  import { ref } from "vue";
  import {ElMessageBox} from "element-plus";
  import router from "@/router/index"
  // import workorderForm from "./form"
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const orderList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const prev = ref([]);
  const addCompanyDialogRef = ref(null);
  const fullscreenLoading = ref(false);
  const formOpen = ref(false);

  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 2,
    noContract: 1,
  });

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

  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: "",
    noContract: 1,
    isStop:0,
  });

  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;
    });
  }
 function OrderDisableForm(){
   if(ids.value.length < 1) {
     proxy.$modal
         .msgError("请选择数据")
     return;
   }
   OrderDisable(ids.value).then((response) => {
     proxy.$modal.msgSuccess('停用成功');
     getList();
   });
 }

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

  /** 导出按钮操作 */
  function handleExport() {
    exportNoContract(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;
  }

  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 saveHandler() {
    if (form.value.companyId == null) {
      proxy.$modal.msgError("请选择公司");
      return;
    }
    if (form.value.remark == null || form.value.remark === "") {
      proxy.$modal.msgError("请输入备注");
      return;
    }
    if (form.value.id == null) {
      addWorkOrder(form.value).then((res) => {
        formCancel();
        getList();
      });
    }
  }

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

  function Upgrade() {
    fullscreenLoading.value = true;

    //这个是检查是否有未匹配工单
    checkMatchWorkOrder();
    //这个是完成升级调用的
    // const promise = Promise.resolve(completeUpgrade());
    // promise
  }

  function checkMatchWorkOrder() {
    const promise = checkWorkOrder();
    promise.then((res)=>{
      if(res.msg === "true"){
        fullscreenLoading.value = false;
        return Promise.reject("您尚未完成工单匹配，还有工单缺少合同，请先去补全合同");
      }else{
        fullscreenLoading.value = false;
      return ElMessageBox.confirm("升级后，您的账套将会切换成为标准版，您确定完成吗").then(()=>{
          fullscreenLoading.value = true;
          return completeUpgrade()
        }).catch((e)=>{
        return Promise.reject("取消升级");
      });
      }
    })
      .then((res) => {
      fullscreenLoading.value = false;
        ElMessageBox.alert(res.msg, '消息', {
          confirmButtonText: '确认',
          callback: (action) => {
            router.replace("/").then((res) => {
              router.go(0);
            });
          },
        })
    })
      .catch((e) => {
        fullscreenLoading.value = false;
          if(e !== "取消升级"){
            proxy.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                e +
                "</div>"
                ,
                {dangerouslyUseHTMLString: true}
            );
          }
      });
  }
  getList();
</script>
<style>
  .listbutton{
    display: flex;
    justify-content: space-between;
  }
</style>