<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">
    </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="合同编号" prop="code" width="160" fixed />
        <el-table-column label="客户名称" prop="customerName" min-width="200" fixed />
        <el-table-column label="业务员" prop="userName" width="140" fixed />
        <el-table-column label="合同金额" width="140">
          <template #default="{ row }">
            <div>{{ row.amount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="应付货款" width="140">
          <template #default="{ row }">
            <div>
              <span v-if="row.otherSumAmount">{{ row.otherSumAmount }}</span>
              <span v-else>{{ row.ehsdSumAmount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="税率" width="140">
          <template #default="{ row }">
            <div>13%</div>
          </template>
        </el-table-column>
        <el-table-column label="应退税金额" prop="refundableAmount" width="140" />
        <el-table-column label="包材金额" width="140">
          <template #default="{ row }">
            <div>{{ row.otherCurrency }}{{ row.other }}</div>
          </template>
        </el-table-column>
        <el-table-column label="配件金额" width="140">
          <template #default="{ row }">
            <div>{{ row.otherCurrency }}{{ row.other }}</div>
          </template>
        </el-table-column>
        <el-table-column label="拖车费" width="140">
          <template #default="{ row }">
            <div>{{ row.trailerFeeCurrency }}{{ row.trailerFee }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报关费" width="140">
          <template #default="{ row }">
            <div>{{ row.customsFeeCurrency }}{{ row.customsFee }}</div>
          </template>
        </el-table-column>
        <el-table-column label="代理费" width="140">
          <template #default="{ row }">
            <div>{{ row.agencyFeeCurrency }}{{ row.agencyFee }}</div>
          </template>
        </el-table-column>
        <el-table-column label="港杂费" width="140">
          <template #default="{ row }">
            <div>{{ row.portMixedFeeCurrency }}{{ row.portMixedFee }}</div>
          </template>
        </el-table-column>
        <el-table-column label="验货红包" width="140">
          <template #default="{ row }">
            <div>{{ row.inspectionRedPackCurrency }}{{ row.inspectionRedPack }}</div>
          </template>
        </el-table-column>
        <el-table-column label="佣金" width="140">
          <template #default="{ row }">
            <div>{{ row.commissionCurrency }}{{ row.commission }}</div>
          </template>
        </el-table-column>
        <el-table-column label="其他" width="140">
          <template #default="{ row }">
            <div>{{ row.otherCurrency }}{{ row.other }}</div>
          </template>
        </el-table-column>
        <el-table-column label="收入总计" prop="incomeAmount" width="140" />
        <el-table-column label="支出总计" prop="expenditureAmount" width="140" />
        <el-table-column label="毛利率" width="140">
          <template #default="{ row }">
            <div>{{ row.grossRate }}%</div>
          </template>
        </el-table-column>
        <el-table-column label="毛利" prop="gross" width="140" />
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="{ row }">
            <div>
              <el-button type="primary" @click="changeExchangeRate(row)" link>汇率</el-button>
              <el-button type="primary" @click="changeBudget(row)" 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
                    onmousewheel="return false;"
                    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
                    onmousewheel="return false;"
                    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>

    <el-dialog title="预算" v-if="openBudget" v-model="openBudget" width="400">
      <byForm :formConfig="formBudgetConfig" :formOption="formOption" v-model="formBudgetData.data" ref="budget">
        <template #budgetMoney>
          <div style="width: 100%">
            <el-form-item label="拖车费" prop="trailerFee">
              <el-input v-model="formBudgetData.data.trailerFee" placeholder="请输入拖车费" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.trailerFeeCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="报关费" prop="customsFee" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.customsFee" placeholder="请输入报关费" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.customsFeeCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="代理费" prop="agencyFee" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.agencyFee" placeholder="请输入代理费" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.agencyFeeCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="港杂费" prop="portMixedFee" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.portMixedFee" placeholder="请输入港杂费" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.portMixedFeeCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="验货红包" prop="inspectionRedPack" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.inspectionRedPack" placeholder="请输入验货红包" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.inspectionRedPackCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="佣金" prop="commission" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.commission" placeholder="请输入佣金" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.commissionCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="其他" prop="other" style="margin-top: 20px">
              <el-input v-model="formBudgetData.data.other" placeholder="请输入其他" class="input-with-select">
                <template #prepend>
                  <el-select v-model="formBudgetData.data.otherCurrency" placeholder="请选择货币" style="width: 115px">
                    <el-option v-for="(item, index) in accountCurrency" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openBudget = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitBudgetForm()" 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 sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    userId: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      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("/contract/getProfitBudgetPage", 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("/contract/edit", data).then(
      () => {
        ElMessage({
          message: "保存成功",
          type: "success",
        });
        openChange.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const openBudget = ref(false);
const budget = ref(null);
const formBudgetData = reactive({
  data: {},
});
const formBudgetConfig = computed(() => {
  return [
    {
      type: "title",
      title: "合同信息",
      label: "",
    },
    {
      type: "input",
      prop: "code",
      label: "合同编号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "customerName",
      label: "客户名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "userName",
      label: "业务员",
      itemType: "text",
      disabled: true,
    },
    {
      type: "title",
      title: "预算金额",
      label: "",
    },
    {
      type: "slot",
      slotName: "budgetMoney",
      label: "",
    },
  ];
});
const changeBudget = (row) => {
  formBudgetData.data = {
    id: row.id,
    code: row.code,
    customerName: row.customerName,
    userName: row.userName,
    trailerFeeCurrency: row.trailerFeeCurrency,
    trailerFee: row.trailerFee,
    customsFeeCurrency: row.customsFeeCurrency,
    customsFee: row.customsFee,
    agencyFeeCurrency: row.agencyFeeCurrency,
    agencyFee: row.agencyFee,
    portMixedFeeCurrency: row.portMixedFeeCurrency,
    portMixedFee: row.portMixedFee,
    inspectionRedPackCurrency: row.inspectionRedPackCurrency,
    inspectionRedPack: row.inspectionRedPack,
    commissionCurrency: row.commissionCurrency,
    commission: row.commission,
    otherCurrency: row.otherCurrency,
    other: row.other,
  };
  openBudget.value = true;
};
const submitBudgetForm = () => {
  proxy.post("/contract/edit", formBudgetData.data).then(() => {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    openBudget.value = false;
    getList();
  });
};
</script>

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