<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="primary" size="small" icon="Plus" @click="handleAdd"
        v-hasPermi="['business:archive:order:add']">新增</el-button>

      <!-- <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['business:archive:order:remove']">删除</el-button> -->
      <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="Delete" :disabled="single" @click="handleAlter" v-if="viewAlter()">
              合同变更</el-dropdown-item>
            <el-dropdown-item icon="Delete" :disabled="single" @click="handleDissolution" v-if="viewDissolution()">
              合同解除</el-dropdown-item>
            <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete" v-if="viewDelete()">
              删除合同</el-dropdown-item>
            <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleBinDelete" v-if="viewBinDelete()">
              放入回收站</el-dropdown-item>
            <el-dropdown-item icon="Download" @click="handleExport" v-if="viewExport()"
              v-hasPermi="['business:archive:order:export']">
              导出</el-dropdown-item>
            <el-dropdown-item icon="Upload" @click="handleImport" v-hasPermi="['business:archive:order:export']"
              v-if="viewExport()">导入</el-dropdown-item>
            <!-- <el-dropdown-item type="warning" size="small" icon="Download" @click="handleArea"
              v-hasPermi="['business:archive:order:export']"> area</el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!-- <el-button type="warning" size="small" icon="Download" @click="handleExport"
        v-hasPermi="['business:archive:order:export']">导出</el-button> -->
      <!--<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </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" size="small" placeholder="请输入客户名称" clearable style="width: 120px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同编号：" prop="contractNo">
        <el-input v-model="queryParams.contractNo" size="small" placeholder="请输入合同编号" clearable style="width: 120px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户标签：">
        <el-select v-model="queryParams.customerLabelId" size="small" style="width: 120px" multiple>
          <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-input v-model="queryParams.boss" size="small" placeholder="请输入甲方名称" clearable style="width: 120px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同类型：" prop="contractType">
        <el-select size="small" v-model="queryParams.contractType" placeholder="合同类型" clearable style="width: 120px">
          <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务类型：" prop="serviceType">
        <el-select size="small" v-model="queryParams.serviceType" placeholder="服务类型" clearable style="width: 120px">
          <el-option v-for="item in serviceTypes" :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" 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>

    <!-- 列表区 -->
    <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="companyName" min-width="250" />
      <el-table-column label="税号" align="center" prop="socialCreditCode" min-width="200" />
      <el-table-column label="合同编号" align="center" prop="contractNo" min-width="150" />
      <el-table-column label="签约日期" align="center" prop="formDate" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.formDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签约金额" header-align="center" align="right" prop="trueAmount" width="80">
        <template #default="scope">{{
          scope.row.trueAmount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, "$&,")
          }}</template>
      </el-table-column>
      <el-table-column label="签单人" align="center" prop="signerName" min-width="120" />
      <el-table-column label="合同来源" align="center" prop="sourceCategoryName" min-width="120" />
      <el-table-column label="客户标签" align="center" prop="customerLabelName" min-width="120" />

      <el-table-column label="甲方" align="center" prop="boss" min-width="120" />
      <el-table-column label="审核状态" align="center" prop="verifyStatus" width="110">
        <template #default="scope">
          <dict-tag :options="contract_verify_status" :value="scope.row.verifyStatus" />
        </template>
      </el-table-column>
      <el-table-column label="合同类型" align="center" prop="contractType" width="80">
        <template #default="scope">
          {{ scope.row.contractType === 0 ? "新签" : "续签" }}
        </template>
      </el-table-column>
      <el-table-column label="服务类型" align="center" prop="serviceType" width="80">
        <template #default="scope">
          {{ scope.row.serviceType === 1 ? "循环" : "代办" }}
        </template>
      </el-table-column>
      <el-table-column label="合同状态" width="110" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="contract_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="130" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:archive:order:edit']">查看</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
            v-hasPermi="['business:archive:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <contract-form ref="contractRef" :get-list="getList" />
    <import-excel-dialog ref="importExcelDialogRef" :get-list="getList" />
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-dialog title="更多搜索" v-model="moreSearch" width="720px" append-to-body size="small" draggable
      :close-on-click-modal="false">
      <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" placeholder="请输入客户名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="服务类型：" prop="serviceType">
              <el-select size="small" v-model="queryParams.serviceType" placeholder="合同类型" clearable
                style="width: 100%">
                <el-option v-for="item in serviceTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="代理记账：" prop="isKeepAccount">
              <el-select size="small" v-model="queryParams.isKeepAccount" placeholder="是否记账" clearable
                style="width: 100%">
                <el-option v-for="item in yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="公积金代缴：" prop="isHousingFund">
              <el-select size="small" v-model="queryParams.isHousingFund" placeholder="是否代缴公积金" clearable
                style="width: 100%">
                <el-option v-for="item in yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="注册：" prop="isRegister">
              <el-select size="small" v-model="queryParams.isRegister" placeholder="是否注册" clearable style="width: 100%">
                <el-option v-for="item in yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型：" prop="contractType">
              <el-select size="small" v-model="queryParams.contractType" placeholder="服务类型" clearable
                style="width: 100%">
                <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="签约日期：" prop="formDate">
              <el-date-picker v-model="queryParams.formDate" type="daterange" clearable format="YYYY - MM - DD "
                value-format="YYYY-MM-DD" range-separator="至" start-placeholder="业务日期" end-placeholder="业务日期"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="社保代缴：" prop="isSocialSecurity">
              <el-select size="small" v-model="queryParams.isSocialSecurity" placeholder="是否代缴社保" clearable
                style="width: 100%">
                <el-option v-for="item in yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="返税申报：" prop="isReturnTax">
              <el-select size="small" v-model="queryParams.isReturnTax" placeholder="是否申报返税" clearable
                style="width: 100%">
                <el-option v-for="item in yesOrNo" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="变更：" prop="isAlter">
              <el-select size="small" v-model="queryParams.isAlter" placeholder="是否变更" clearable style="width: 100%">
                <el-option v-for="item in yesOrNo" :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="Order">
  import { dissolutionOrder } from "../../../../api/business/crm/contract";
  import contractForm from "./form";
  import useUserStore from "@/store/modules/user";
  import {
    listOrder,
    delOrder,
    delBinOrder,
    exportOrder,
  } from "@/api/business/crm/contract";
  import { listLableNoPage } from "@/api/business/lable";
  import importExcelDialog from "./importExcelDialog.vue";
  import { yesOrNo } from "@/utils/default";
  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 permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  const importExcelDialogRef = ref(null);
  const moreSearch = ref(false);
  const options = ref([]);
  const contractTypes = ref([
    {
      label: "新签",
      value: 0,
    },
    {
      label: "续签",
      value: 1,
    },
  ]);

  const serviceTypes = ref([
    {
      label: "循环服务",
      value: 1,
    },
    {
      label: "单次服务",
      value: 2,
    },
  ]);

  const { contract_verify_status } = proxy.useDict("contract_verify_status");
  const { contract_status } = proxy.useDict("contract_status");
  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    fromId: 0,
    orderByColumn: "create_time",
    category: null,
    code: null,
    name: null,
    shortName: null,
    companyName: null,
    oldName: null,
    owner: null,
    phone: null,
    email: null,
    contactAddress: null,
    source: null,
    type: null,
    socialCreditCode: null,
    mainBusiness: null,
    legalRepresentative: null,
    foundationDate: null,
    licenceDate: null,
    businessStartDate: null,
    businessEndDate: null,
    isPermanentlyEffective: null,
    registerMoney: null,
    registerMoneyUnit: null,
    provinceCode: null,
    province: null,
    cityCode: null,
    city: null,
    districtCode: null,
    district: null,
    address: null,
    businessField: null,
    taxType: null,
    isZero: null,
    competentTaxAuthority: null,
    taxCollectorName: null,
    taxCollectorPhone: null,
    taxMonth: null,
    openingBank: null,
    bankAccount: null,
    annualIncome: null,
    governmentAccountNo: null,
    governmentPassword: null,
    socialSecurityAccountNo: null,
    socialSecurityPassword: null,
    employeePassword: null,
    housingFundPassword: null,
    housingFundUnitAccount: null,
    housingFundDeductionPassword: null,
    collectionMethod: null,
    quotaAmount: null,
    isPayOnWindow: null,
    isFirstSocialSecurity: null,
    isFirstHousingFund: null,
    customerLabelId: [],
    boss: null
  });
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /***********************  方法区  ****************************/

  /** 查询company列表 */
  function getList() {
    loading.value = true;
    listOrder(queryParams.value).then((response) => {
      orderList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  function viewAlter() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:archive:order:alter")
    );
  }

  function viewDissolution() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:archive:order:dissolution")
    );
  }
  function getOption() {
    listLableNoPage().then(res => {
      options.value = res.data
    })
  }
  function viewDelete() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:archive:order:remove")
    );
  }

  function viewBinDelete() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:archive:order:bin")
    );
  }
  function viewExport() {
    return (
      permissions.includes(all_permission) ||
      permissions.includes("business:archive:order:export")
    );
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.customerLabelId = [];
    queryParams.value.formDate = [];
    queryParams.value.boss = null
    handleQuery();
  }

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

  /** 新增按钮操作 */
  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 delOrder(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 放入回收站按钮操作 */
  function handleBinDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认选中的数据项放入回收站？")
      .then(function () {
        return delBinOrder(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("数据已放入回收站！");
      })
      .catch(() => { });
  }

  function handleAlter() {
    const id = ids.value;
    const row = orderList.value.find((item) => item.id === ids.value[0]);
    if (row.verifyStatus == 0) {
      proxy.$modal.msgError("未审核合同无法变更！");
      return;
    }
    if (row.status == 9) {
      proxy.$modal.msgError("已解除合同无法变更！");
      return;
    }
    proxy.$refs.contractRef.openSimple(id, "alterOrder");
  }

  function handleDissolution() {
    const row = orderList.value.find((item) => item.id === ids.value[0]);
    console.log(row);
    if (row.verifyStatus == 0) {
      proxy.$modal.msgError("未审核合同无法解除！");
      return;
    }
    proxy.$modal
      .confirm("是否确认解除合同？")
      .then(function () {
        return dissolutionOrder(row);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("解除成功！");
      });
    // .catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    // proxy.download(
    //   "business/archive/order/export",
    //   {
    //     ...queryParams.value,
    //   },
    //   `合同导出_${new Date().getTime()}.xlsx`
    // );
    exportOrder(queryParams.value);
  }

  function handleImport() {
    importExcelDialogRef.value.open();
  }

  getList();
  getOption();
</script>