<template>
  <div class="tenant">
    <byTable
      :hideTable="true"
      :hidePagination="true"
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      :selectConfig="selectConfig"
      highlight-current-row
      :action-list="[
        {
          text: '默认汇率',
          action: () => openModal(),
        },
      ]"
      @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="" width="120">
            <template #default="{ row }">
              <div>
                {{ row.currency }} {{ moneyFormat(row.contractAmount, 2) }}
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="收入（CNY）">
          <el-table-column label="合同到账" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.contractArrival, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="退税" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.taxReturnMoney, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="其他收入" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.otherIncome, 2) }}</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="采购合同金额">
          <el-table-column label="" width="120">
            <template #default="{ row }">
              <div>
                {{ row.currency }} {{ moneyFormat(row.purchaseAmount, 2) }}
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="支出（CNY）">
          <el-table-column label="支付货款" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.payForGoods, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="其他支出" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.otherExpenses, 2) }}</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="统计">
          <el-table-column label="收入合计" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.totalIncome, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="支出合计" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.totalExpenses, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="毛利" width="120">
            <template #default="{ row }">
              <div>{{ moneyFormat(row.grossProfit, 2) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="毛利率" prop="grossProfitMargin" width="120">
            <template #default="{ row }">
              <div style="width: 100%">{{ row.grossProfitMargin }}%</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作" align="center" width="170" fixed="right">
          <template #default="{ row }">
            <div>
              <el-button type="primary" @click="changeExchangeRate(row)" link
                >调整汇率</el-button
              >
              <el-button
                type="primary"
                @click="clickSettlement(row)"
                v-if="row.settlementStatus === 0"
                link
                >结算</el-button
              >
              <el-button
                type="primary"
                @click="clickCancelSettlement(row)"
                v-else
                link
                >取消结算</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <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="dialogVisible"
      v-model="dialogVisible"
      width="600"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="submit"
      >
        <template #currencyList>
          <el-table
            :data="formData.data.list"
            style="width: 100%"
            v-loading="loadingDialog"
          >
            <el-table-column label="币种">
              <template #default="{ row }">
                <div>{{ dictValueLabel(row.type, accountCurrency) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="兑 CHY 汇率">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'list.' + $index + '.rate'"
                  :rules="rules.rate"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.rate"
                    placeholder="请输入兑 CHY 汇率"
                    style="width: 100%"
                    :precision="6"
                    :controls="false"
                    :min="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large"
          >确 定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      title="调整汇率"
      v-if="openChange"
      v-model="openChange"
      width="600"
    >
      <byForm
        :formConfig="formChangeConfig"
        :formOption="formOption"
        v-model="formChangeData.data"
        :rules="rules"
        ref="change"
      >
        <template #currencyList>
          <el-table
            :data="formChangeData.data.list"
            style="width: 100%"
            v-loading="loadingDialog"
          >
            <el-table-column label="币种">
              <template #default="{ row }">
                <div>{{ dictValueLabel(row.type, accountCurrency) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="兑 CHY 汇率">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'list.' + $index + '.rate'"
                  :rules="rules.rate"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.rate"
                    placeholder="请输入兑 CHY 汇率"
                    style="width: 100%"
                    :precision="6"
                    :controls="false"
                    :min="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </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 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 };
  loading.value = true;
  proxy
    .post("/saleStatement/getProfitSettlement", sourceList.value.pagination)
    .then((res) => {
      sourceList.value.data = res.rows;
      sourceList.value.pagination.total = res.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
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 formData = reactive({
  data: {
    list: [],
  },
});
const formConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "currencyList",
      slotName: "currencyList",
      label: "",
    },
  ];
});
const rules = ref({
  rate: [{ required: true, message: "请输入兑 CHY 汇率", trigger: "blur" }],
});
const openModal = () => {
  if (accountCurrency.value && accountCurrency.value.length > 0) {
    formData.data = {
      list: accountCurrency.value.map((item) => {
        return {
          id: "",
          type: item.value,
          rate: 1,
        };
      }),
    };
  } else {
    formData.data = {
      list: [],
    };
  }
  loadingDialog.value = true;
  dialogVisible.value = true;
  proxy.post("/currencyRate/list", {}).then(
    (res) => {
      if (res && res.length > 0 && formData.data.list.length > 0) {
        formData.data.list = formData.data.list.map((item) => {
          for (let i = 0; i < res.length; i++) {
            if (item.type === res[i].type) {
              item.id = res[i].id;
              item.rate = res[i].rate;
              break;
            }
          }
          return {
            ...item,
          };
        });
      }
      loadingDialog.value = false;
    },
    (err) => {
      console.log(err);
      loadingDialog.value = false;
    }
  );
};
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: {
    list: [],
  },
});
const formChangeConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "currencyList",
      slotName: "currencyList",
      label: "",
    },
  ];
});
const changeExchangeRate = (row) => {
  formChangeData.data = {
    id: row.contractId,
    list: [],
  };
  if (accountCurrency.value && accountCurrency.value.length > 0) {
    formChangeData.data.list = accountCurrency.value.map((item) => {
      return {
        type: item.value,
        rate: 1,
      };
    });
  }
  loadingDialog.value = true;
  openChange.value = true;
  if (row.currencyRateJson) {
    let currencyRateJson = JSON.parse(row.currencyRateJson);
    formChangeData.data.list = formChangeData.data.list.map((item) => {
      for (let i = 0; i < currencyRateJson.length; i++) {
        if (item.type === currencyRateJson[i].type) {
          item.rate = currencyRateJson[i].rate;
          break;
        }
      }
      return {
        ...item,
      };
    });
    loadingDialog.value = false;
  } else {
    proxy.post("/currencyRate/list", {}).then(
      (res) => {
        if (res && res.length > 0 && formChangeData.data.list.length > 0) {
          formChangeData.data.list = formChangeData.data.list.map((item) => {
            for (let i = 0; i < res.length; i++) {
              if (item.type === res[i].type) {
                item.rate = res[i].rate;
                break;
              }
            }
            return {
              ...item,
            };
          });
        }
        loadingDialog.value = false;
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  }
};
const submitChangeForm = () => {
  change.value.handleSubmit(() => {
    loadingDialog.value = true;
    let data = {};
    data.id = formChangeData.data.id;
    data.currencyRateJson = JSON.stringify(formChangeData.data.list);
    proxy.post("/saleStatement/update", data).then(
      () => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        openChange.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const clickSettlement = (row) => {
  const data = {
    id: row.contractId,
    settlementStatus: 1,
  };
  proxy.post("/saleStatement/update", data).then(() => {
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    getList();
  });
};
const clickCancelSettlement = (row) => {
  proxy
    .post("/saleStatement/update", {
      id: row.contractId,
      settlementStatus: 0,
    })
    .then(() => {
      ElMessage({
        message: "操作成功",
        type: "success",
      });
      getList();
    });
};
</script>

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