<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: selectRow,
        }"
        :action-list="[
          {
            text: '合并付款',
            disabled: selectData.length === 0,
            action: () => start(20),
          },
        ]"
        @get-list="getList"
      >
        <template #contractCode="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickContractCode(item)"
          >
            {{ item.contractCode }}
          </div>
        </template>

        <template #paymentStatus="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickArrivalStatus(item)"
          >
            {{ dictValueLabel(item.arrivalStatus, arrivalStatus) }}
          </div>
        </template>

        <template #btn="{ item }">
          <div>
            <el-button type="primary" link @click="start(10)">付款</el-button>

            <el-button type="primary" link @click="handleEdit(item, 88)"
              >结束</el-button
            >
            <el-button type="primary" link @click="handleEdit(item, 99)"
              >清空</el-button
            >
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加售后记录' : '添加跟进记录'"
      v-model="dialogVisible"
      width="800"
      v-loading="submitLoading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #details>
          <div style="width: 100%">
            <el-table :data="formData.data.afterSaleDetailList">
              <el-table-column prop="productCode" label="采购单号" />
              <el-table-column prop="productName" label="采购金额" />
              <el-table-column prop="productSpec" label="已付款金额" />
              <el-table-column prop="quantity" label="付款金额" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'afterSaleDetailList.' + $index + '.quantity'"
                    :rules="rules.quantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.quantity"
                      :precision="2"
                      :controls="false"
                      :min="0"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisibleOne"
      title="付款记录"
      width="500"
      append-to-body
      destroy-on-close
    >
      <div>
        <el-timeline :reverse="false">
          <el-timeline-item
            placement="top"
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.handleTime"
          >
            <div>
              跟进人：{{ activity.handleUserName }}
              <span
                >（{{
                  dictValueLabel(activity.status, afterSalesStatus)
                }}）</span
              >
            </div>
            <div style="margin-top: 5px">跟进记录： {{ activity.remark }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="dialogVisibleOne = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import FileUpload from "@/components/FileUpload/index";
import { computed, defineComponent, ref } from "vue";
import { getToken } from "@/utils/auth";
import SelectProduct from "@/components/WDLY/product/SelectProduct";
import useUserStore from "@/store/modules/user";

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadData = ref({});
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "",
    keyword: "",
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let activities = ref([]);
let modalType = ref("add");

let rules = ref({
  detailedAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
  handleUserId: [
    { required: true, message: "请选择跟进人", trigger: "change" },
  ],
});
const { proxy } = getCurrentInstance();
const afterSalesType = ref([]);
const afterSalesStatus = ref([]);
const selectConfig = computed(() => [
  {
    label: "到货状态",
    prop: "type",
    data: afterSalesType.value,
  },
  {
    label: "付款状态",
    prop: "status",
    data: afterSalesStatus.value,
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "采购单号",
        slot: "contractCode",
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, afterSalesType.value);
      // },
    },
    {
      attrs: {
        label: "供应商",
        prop: "customerName",
      },
    },
    {
      attrs: {
        label: "收获仓库",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "采购金额",
        prop: "address",
      },
      render() {
        return proxy.moneyFormat(20, 2);
      },
    },
    {
      attrs: {
        label: "已付款金额",
        prop: "cause",
      },
      render() {
        return proxy.moneyFormat(20, 2);
      },
    },
    {
      attrs: {
        label: "采购人",
        prop: "createTime",
        width: 100,
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "createTime",
        width: 155,
      },
    },
    {
      attrs: {
        label: "到货状态",
        prop: "createTime",
        width: 100,
      },
    },
    {
      attrs: {
        label: "付款状态",
        slot: "paymentStatus",
        width: 100,
      },
    },
    {
      attrs: {
        label: "操作",
        slot: "btn",
        width: "180",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);

let formConfig = computed(() => [
  {
    type: "input",
    prop: "type",
    label: "供应商",
    disabled: true,
  },
  {
    type: "date",
    itemType: "datetime",
    prop: "type",
    label: "付款时间",
    format: "YYYY-MM-DD HH:mm:ss",
  },
  {
    type: "number",
    prop: "aa",
    label: "付款金额",
    precision: 2,
    min: 0,
    controls: false,
  },
  {
    type: "title",
    title: "付款明细",
  },
  {
    type: "slot",
    slotName: "details",
    label: "",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/afterSaleRecord/page", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const rowData = ref({});

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.afterSaleDetailList;
    if (!list.length > 0)
      return ElMessage({
        message: `请关联商品！`,
        type: "info",
      });
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (e.quantity == 0) {
        return ElMessage({
          message: `数量不能为0！`,
          type: "info",
        });
      }
    }
    proxy.post("ada", formData.data).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisible.value = false;
        setTimeout(() => {
          submitLoading.value = false;
        }, 5000);
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/supplierInfo/detail", { id: row.id }).then((res) => {
    proxy
      .post("/fileInfo/getList", { businessIdList: [row.id] })
      .then((fileObj) => {
        fileList.value = fileObj[row.id] || [];
        fileListCopy.value = [...fileList.value];
        getCityData(res.countryId, "20");
        getCityData(res.provinceId, "30");
        res.type = res.type + "";
        res.victoriatouristJson = JSON.parse(res.victoriatouristJson);
        formData.data = res;
        dialogVisible.value = true;
      });
  });
};

const handleClickFile = (row) => {
  ElMessage({
    message: "数据请求中，请稍后！",
    type: "success",
  });
  let id = row.id;
  proxy.post("/fileInfo/getList", { businessIdList: [id] }).then((res) => {
    const file = res[id][0];
    window.open(file.fileUrl, "_blank");
  });
};

const handleClose = (index) => {
  if (fileListCopy.value.length === 1) {
    return ElMessage({
      message: "最后一个附件啦！",
      type: "info",
    });
  }
  fileList.value.splice(index, 1);
  fileListCopy.value.splice(index, 1);
};

const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);

const getCityData = (id, type, flag) => {
  proxy.post("/customizeArea/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (flag) {
        formData.data.provinceId = "";
        formData.data.provinceName = "";
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (flag) {
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else {
      countryData.value = res;
    }
  });
};
const handleSelect = (row) => {
  const flag = formData.data.afterSaleDetailList.some(
    (x) => x.productId === row.id
  );
  if (flag)
    return ElMessage({
      message: "该商品已选择",
      type: "info",
    });
  formData.data.afterSaleDetailList.push({
    productName: row.name,
    productCode: row.code,
    productSpec: row.spec,
    productId: row.id,
    quantity: null,
    remark: "",
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

const handleRemove = (index) => {
  formData.data.afterSaleDetailList.splice(index, 1);
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};

const getDict = () => {
  proxy.getDict(["after_sale_type", "after_sale_status"]).then((res) => {
    afterSalesType.value = res["after_sale_type"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    afterSalesStatus.value = res["after_sale_status"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};

const selectData = ref([]);
const selectDataOne = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
watch(selectData, (newVal, oldVal) => {
  if (newVal.length == 0) {
    sourceList.value.data.forEach((x) => {
      if (x.status <= 30) {
        x.isCheck = true;
      } else {
        x.isCheck = false;
      }
    });
  } else if (newVal.length == 1) {
    const current = newVal[0];
    sourceList.value.data.forEach((x) => {
      if (x.receiptWarehouseId !== current.receiptWarehouseId) {
        x.isCheck = false;
      }
    });
  }
});

const start = (type, data) => {
  modalType.value = "add";
  let ids = [];
  let row = {};
  if (type === 10) {
    selectDataOne.value = [data];
    // row = selectDataOne.value[0];
    // ids = selectDataOne.value.map((x) => x.id).join();
  } else if (type === 20) {
    // ids = selectData.value.map((x) => x.id).join();
    // row = selectData.value[0];
  }
  dialogVisible.value = true;
};

getCityData("0");
getList();
getDict();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>