<template>
  <div class="tenant">
    <div class="content">
      <div style="padding: 20px 0 0 20px">
        <el-form :inline="true" :model="queryForm">
          <el-form-item label="年份">
            <el-date-picker
              v-model="queryForm.time"
              type="year"
              placeholder="请选择"
              format="YYYY"
              value-format="YYYY"
              clearable
              @change="onQuery"
            />
          </el-form-item>
          <el-form-item label="业务员">
            <el-select
              v-model="queryForm.userId"
              placeholder="请选择"
              clearable
              @change="onQuery"
            >
              <el-option
                v-for="item in userList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <byTable
        :hideTable="true"
        :hidePagination="true"
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        :action-list="[]"
        @get-list="getList"
      >
        <template #amount="{ item }">
          <div></div>
        </template>
      </byTable>
      <div
        style="padding: 0 20px 20px 20px; background-color: white"
        v-if="rateStatus"
      >
        <el-table v-loading="loading" :data="sourceList.data">
          <el-table-column label="合同编号">
            <el-table-column label="" prop="contractCode" width="160" />
          </el-table-column>
          <el-table-column label="客户名称">
            <el-table-column label="" prop="customerName" min-width="200" />
          </el-table-column>
          <el-table-column label="业务员">
            <el-table-column label="" prop="userName" width="120" />
          </el-table-column>
          <el-table-column label="销售合同金额">
            <el-table-column label="" prop="contractAmount" width="120" />
          </el-table-column>
          <el-table-column label="收入">
            <el-table-column
              label="合同到账"
              prop="contractArrival"
              width="120"
            />
            <el-table-column label="其他收入" prop="otherIncome" width="120" />
          </el-table-column>
          <el-table-column label="采购合同金额">
            <el-table-column label="" prop="purchaseAmount" width="120" />
          </el-table-column>
          <el-table-column label="支出">
            <el-table-column label="支付货款" prop="payForGoods" width="120" />
            <el-table-column
              label="其他支出"
              prop="otherExpenses"
              width="120"
            />
          </el-table-column>
          <el-table-column label="统计">
            <el-table-column label="收入合计" prop="totalIncome" width="120" />
            <el-table-column
              label="支出合计"
              prop="totalExpenses"
              width="120"
            />
            <el-table-column label="毛利" prop="grossProfit" width="120" />
            <el-table-column
              label="毛利率"
              prop="grossProfitMargin"
              width="120"
            />
          </el-table-column>
          <el-table-column label="提成">
            <el-table-column label="售后" prop="afterSalesAmount" width="120" />
            <el-table-column label="公共" prop="publicAmount" width="120" />
            <el-table-column
              label="总办"
              prop="haveOverallAmount"
              width="120"
            />
            <el-table-column
              label="部门提成"
              prop="departmentalCommission"
              width="120"
            />
            <el-table-column
              label="个人提成"
              prop="personalCommission"
              width="120"
            />
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
          >
            <template #default="{ row }">
              <div>
                <el-button type="primary" @click="changeExchangeRate(row)" link
                  >调整</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row style="padding: 20px" justify="end" type="flex">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="sourceList.pagination.pageNum"
          :page-size="sourceList.pagination.pageSize"
          :total="sourceList.pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-row>
    </div>

    <el-dialog title="调整" v-if="openChange" v-model="openChange" width="700">
      <byForm
        :formConfig="formChangeConfig"
        :formOption="formOption"
        v-model="formChangeData.data"
        :rules="rules"
        ref="change"
      >
        <template #afterSalesRatioSlot>
          <div style="width: 100%">
            <el-row>
              <el-col :span="4">
                <el-input
                  v-model="formChangeData.data.afterSalesRatio"
                  placeholder="请输入"
                  :formatter="(val) => val.replace(/[^\d]/g, '')"
                  :parser="(val) => val.replace(/[^\d]/g, '')"
                >
                  <template #suffix>
                    <span> % </span>
                  </template></el-input
                >
              </el-col>
              <el-co :span="20" style="padding-left: 10px"> 默认 4% </el-co>
            </el-row>
          </div>
        </template>
        <template #publicRatioSlot>
          <div style="width: 100%">
            <el-row>
              <el-col :span="4">
                <el-input
                  v-model="formChangeData.data.publicRatio"
                  placeholder="请输入"
                  :formatter="(val) => val.replace(/[^\d]/g, '')"
                  :parser="(val) => val.replace(/[^\d]/g, '')"
                >
                  <template #suffix>
                    <span> % </span>
                  </template></el-input
                >
              </el-col>
              <el-co :span="20" style="padding-left: 10px"> 默认 6% </el-co>
            </el-row>
          </div>
        </template>
        <template #haveOverallRatioSlot>
          <div style="width: 100%">
            <el-row>
              <el-col :span="4">
                <el-input
                  v-model="formChangeData.data.haveOverallRatio"
                  placeholder="请输入"
                  :formatter="(val) => val.replace(/[^\d]/g, '')"
                  :parser="(val) => val.replace(/[^\d]/g, '')"
                >
                  <template #suffix>
                    <span> % </span>
                  </template></el-input
                >
              </el-col>
              <el-co :span="20" style="padding-left: 10px"> 默认 5% </el-co>
            </el-row>
          </div>
        </template>
        <template #departmentalRatioSlot>
          <div style="width: 100%">
            <el-row>
              <el-col :span="4">
                <el-input
                  v-model="formChangeData.data.departmentalRatio"
                  placeholder="请输入"
                  :formatter="(val) => val.replace(/[^\d]/g, '')"
                  :parser="(val) => val.replace(/[^\d]/g, '')"
                >
                  <template #suffix>
                    <span> % </span>
                  </template></el-input
                >
              </el-col>
              <el-co :span="20" style="padding-left: 10px">
                默认 33%。即：部门提成 = （总收入 - 总支出 - 售后 - 公共 -
                总办） * 部门占比
              </el-co>
            </el-row>
          </div>
        </template>
        <template #personalRatioSlot>
          <div style="width: 100%">
            <el-row>
              <el-col :span="4">
                <el-input
                  v-model="formChangeData.data.personalRatio"
                  placeholder="请输入"
                  :formatter="(val) => val.replace(/[^\d]/g, '')"
                  :parser="(val) => val.replace(/[^\d]/g, '')"
                >
                  <template #suffix>
                    <span> % </span>
                  </template></el-input
                >
              </el-col>
              <el-co :span="20" style="padding-left: 10px">
                默认 17%。即：个人提成 = （总收入 - 总支出 - 售后 - 公共 -
                总办）* 个人占比
              </el-co>
            </el-row>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openChange = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitChangeForm()" size="large"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const accountCurrency = ref([]);
const userList = ref([]);
const queryForm = reactive({
  userId: "",
  time: "",
});
const settlementStatus = ref([
  {
    label: "未结算",
    value: "0",
  },
  {
    label: "已结算",
    value: "1",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    settlementStatus: "",
    userId: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    // {
    //   label: "是否完结",
    //   prop: "settlementStatus",
    //   data: settlementStatus.value,
    // },
    // {
    //   label: "业务员",
    //   prop: "userId",
    //   data: userList.value,
    // },
  ];
});
const config = computed(() => {
  return [];
});
const getDict = () => {
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "account_currency",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        accountCurrency.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
        judgeRate();
      } else {
        ElMessage("请先添加货币");
      }
    });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
};
const getList = async (req) => {
  sourceList.value.pagination = {
    ...sourceList.value.pagination,
    ...req,
    ...queryForm,
  };
  loading.value = true;
  proxy.post("/commission/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

const onQuery = () => {
  getList();
};

const rateStatus = ref(false);
const judgeRate = () => {
  proxy.post("/currencyRate/list", {}).then(
    (res) => {
      if (res && res.length > 0) {
        for (let i = 0; i < accountCurrency.value.length; i++) {
          let currencyStatus = true;
          for (let j = 0; j < res.length; j++) {
            if (accountCurrency.value[i].value === res[j].type) {
              currencyStatus = false;
              break;
            }
          }
          if (currencyStatus) {
            return ElMessage("请先完成默认汇率的配置");
          }
        }
        rateStatus.value = true;
        getList();
      } else {
        ElMessage("请先完成默认汇率的配置");
      }
    },
    (err) => {
      console.log(err);
      ElMessage("请先完成默认汇率的配置");
    }
  );
};
getDict();
const handleSizeChange = (val) => {
  sourceList.value.pagination.pageNum = 1;
  sourceList.value.pagination.pageSize = val;
  getList();
};
const handlePageChange = (val) => {
  sourceList.value.pagination.pageNum = val;
  getList();
};
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const rules = ref({
  rate: [{ required: true, message: "请输入兑 CHY 汇率", trigger: "blur" }],
});

const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    proxy.post("/currencyRate/edit", formData.data.list).then(
      () => {
        ElMessage({
          message: "保存成功",
          type: "success",
        });
        dialogVisible.value = false;
        rateStatus.value = true;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const openChange = ref(false);
const change = ref(null);
const formChangeData = reactive({
  data: {},
});
const formChangeConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "afterSalesRatio",
      slotName: "afterSalesRatioSlot",
      label: "售后占比",
    },
    {
      type: "slot",
      prop: "publicRatio",
      slotName: "publicRatioSlot",
      label: "公共占比",
    },
    {
      type: "slot",
      prop: "haveOverallRatio",
      slotName: "haveOverallRatioSlot",
      label: "总办占比",
    },
    {
      type: "slot",
      prop: "departmentalRatio",
      slotName: "departmentalRatioSlot",
      label: "部门占比",
    },
    {
      type: "slot",
      prop: "personalRatio",
      slotName: "personalRatioSlot",
      label: "个人占比",
    },
  ];
});
const rowData = ref({});
const changeExchangeRate = (row) => {
  rowData.value = row;
  proxy.post("/commissionRule/detail", { id: row.id }).then((res) => {
    openChange.value = true;
    formChangeData.data = res;
  });
};

const submitChangeForm = () => {
  change.value.handleSubmit(() => {
    const {
      afterSalesRatio,
      publicRatio,
      haveOverallRatio,
      departmentalRatio,
      personalRatio,
    } = formChangeData.data;
    let sum =
      Number(afterSalesRatio) +
      Number(publicRatio) +
      Number(haveOverallRatio) +
      Number(departmentalRatio) +
      Number(personalRatio);
    if (sum > 100)
      return ElMessage({
        message: "全部占比不可大于100%",
        type: "info",
      });
    proxy
      .post("/saleStatement/settlement", {
        commissionRule: formChangeData.data,
        ...rowData.value,
      })
      .then(
        () => {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          openChange.value = false;
          getList();
        },
        (err) => {
          console.log(err);
        }
      );
  });
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
  .content {
    background-color: white;
  }
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
