<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: select,
        }"
        :action-list="[
          {
            text: '添加售后记录',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #address="{ item }">
          <div>
            {{ item.countryName }}, {{ item.provinceName }} ,
            {{ item.cityName }}, {{ item.detailedAddress }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加售后记录' : '添加跟进记录'"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #address>
          <el-row style="width: 100%">
            <el-col :span="8">
              <el-form-item prop="countryId">
                <el-select
                  v-model="formData.data.countryId"
                  placeholder="国家"
                  @change="(val) => getCityData(val, '20', true)"
                >
                  <el-option
                    v-for="item in countryData"
                    :label="item.chineseName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="provinceId">
                <el-select
                  v-model="formData.data.provinceId"
                  placeholder="省/洲"
                  @change="(val) => getCityData(val, '30', true)"
                >
                  <el-option
                    v-for="item in provinceData"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="cityId">
                <el-select v-model="formData.data.cityId" placeholder="城市">
                  <el-option
                    v-for="item in cityData"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="24">
              <el-form-item prop="detailedAddress">
                <el-input
                  v-model="formData.data.detailedAddress"
                  type="textarea"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template #products>
          <div style="width: 100%">
            <el-button
              type="primary"
              @click="openProduct = true"
              style="margin-bottom: 10px"
            >
              添加
            </el-button>
            <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-column prop="remark" label="备注" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'afterSaleDetailList.' + $index + '.remark'"
                    :inline-message="true"
                  >
                    <el-input v-model="row.remark" placeholder="请输入" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="zip" label="操作" width="100">
                <template #default="{ $index }">
                  <el-button type="primary" link @click="handleRemove($index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>

        <template #fileSlot>
          <div>
            <el-upload
              v-model:fileList="fileList"
              :show-file-list="false"
              class="upload-demo"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              :on-preview="handlePreview"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload"
            >
              <el-button type="primary">选择</el-button>
            </el-upload>
            <div>
              <div style="margin-top: 15px">
                <el-tag
                  style="margin-right: 10px"
                  class="ml-2"
                  type="info"
                  v-for="(item, index) in fileListCopy"
                  :key="index"
                  closable
                  @close="handleClose(index)"
                  >{{ item.fileName }}</el-tag
                >
              </div>
            </div>
          </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="openProduct"
      title="选择商品"
      width="70%"
      append-to-body
    >
      <SelectProduct @handleSelect="handleSelect"></SelectProduct>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openProduct = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisibleOne"
      title="跟进记录"
      width="500"
      append-to-body
    >
      <div style="padding-left: 40px; margin-bottom: 20px">
        <el-button size="mini" @click="openModal('edit')">
          添加跟进记录
        </el-button>
      </div>
      <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
                >（{{ dictDataEcho(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 openProduct = ref(false);
let modalType = ref("add");
let fileList = ref([]);
let fileListCopy = ref([]);

const checkContactNumber = (rule, val, callback) => {
  if (val === "") {
    callback(new Error("请输入联系电话"));
  } else {
    val = "aaa";
  }
  console.log(rule, val, callback, "213");
  // @input="(val) => val.replace(/[^\d]/g, '')"
};
let rules = ref({
  customerId: [
    { required: true, message: "请选择客户名称", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择售后类型", trigger: "change" }],
  countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  provinceId: [{ required: true, message: "请选择省/洲", trigger: "change" }],
  cityId: [{ required: true, message: "请选择城市", trigger: "change" }],
  detailedAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  cause: [{ required: true, message: "请输入售后原因", trigger: "blur" }],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  remark: [{ required: true, message: "请输入跟进记录", trigger: "blur" }],

  status: [{ required: true, message: "请选择售后状态", trigger: "change" }],
  handleTime: [
    { required: true, message: "请选择跟进时间", trigger: "change" },
  ],
  handleUserId: [
    { required: true, message: "请选择跟进人", trigger: "change" },
  ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "售后类型",
    prop: "type",
    data: [],
  },
  {
    label: "售后状态",
    prop: "status",
    data: [],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "售后类型",
        prop: "type",
      },
      render(type) {
        return proxy.dictDataEcho(type, afterSalesType.value);
      },
    },
    {
      attrs: {
        label: "客户名称",
        prop: "customerName",
      },
    },
    {
      attrs: {
        label: "售后时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "所在城市",
        slot: "address",
      },
    },
    {
      attrs: {
        label: "售后原因",
        prop: "cause",
      },
    },

    {
      attrs: {
        label: "售后状态",
        prop: "status",
      },
      render(type) {
        return proxy.dictDataEcho(type, afterSalesStatus.value);
      },
    },

    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "跟进记录",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              openModalOne(row);
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const configData = [
  [
    {
      type: "title",
      title: "售后信息",
    },
    {
      type: "select",
      prop: "type",
      label: "售后类型",
      required: true,
      itemWidth: 51,
      data: [],
    },
    {
      type: "select",
      prop: "customerId",
      label: "客户名称",
      required: true,
      itemWidth: 51,
      isLoad: {
        url: "/customer/page",
        req: {
          pageNum: 1,
          pageSize: 9999,
        },
        labelKey: "name",
        labelVal: "id",
        method: "post",
        resUrl: "rows",
      },
    },
    {
      type: "slot",
      slotName: "address",
      prop: "countryId",
      label: "详细地址",
      required: true,
    },
    {
      type: "input",
      label: "售后原因",
      prop: "cause",
      itemType: "textarea",
    },
    {
      type: "slot",
      slotName: "products",
      label: "关联商品",
    },
  ],
  [
    {
      type: "select",
      prop: "status",
      label: "售后状态",
      required: true,
      itemWidth: 51,
    },
    {
      type: "select",
      prop: "handleUserId",
      label: "跟进人",
      required: true,
      itemWidth: 50,
      isLoad: {
        url: `/tenantUser/list?pageNum=1&pageSize=9999&tenantId=${
          useUserStore().user.tenantId
        }`,
        labelKey: "nickName",
        labelVal: "userId",
        method: "get",
        resUrl: "rows",
      },
    },
    {
      type: "date",
      prop: "handleTime",
      itemType: "datetime",
      label: "跟进时间",
      required: true,
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "nextUserId",
      label: "下一跟进人",
      required: true,
      itemWidth: 51,
      isLoad: {
        url: `/tenantUser/list?pageNum=1&pageSize=9999&tenantId=${
          useUserStore().user.tenantId
        }`,
        labelKey: "nickName",
        labelVal: "userId",
        method: "get",
        resUrl: "rows",
      },
    },
    {
      type: "input",
      label: "跟进记录",
      prop: "remark",
      itemType: "textarea",
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
  ],
];
let formConfig = reactive([]);
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 openModal = (type, row = {}) => {
  modalType.value = type;
  if (type == "add") {
    formConfig = configData[0];
    formData.data = {
      countryId: "China",
      afterSaleDetailList: [],
    };
    getCityData(formData.data.countryId, "20");
  } else if (type == "edit") {
    formConfig = configData[1];
    formData.data = {
      afterSaleRecordId: "",
    };
    fileList.value = [];
    fileListCopy.value = [];
  }
  dialogVisible.value = true;
};
const rowData = ref({});
const openModalOne = (row) => {
  rowData.value = { ...row };
  getRecordList();
};

const getRecordList = () => {
  proxy
    .post("/afterSaleHandle/page", { afterSaleRecordId: rowData.value.id })
    .then((res) => {
      activities.value = res.rows;
      dialogVisibleOne.value = true;
    });
};
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    if (modalType.value == "add") {
      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",
          });
        }
      }
    } else {
      formData.data.fileList =
        fileListCopy.value.map((x) => ({
          id: x.id,
          fileName: x.fileName,
        })) || [];
      formData.data.afterSaleRecordId = rowData.value.id;
    }
    const requestUrl =
      modalType.value == "add"
        ? "/afterSaleRecord/add"
        : "/afterSaleHandle/add";
    submitLoading.value = true;
    proxy.post(requestUrl, formData.data).then(
      (res) => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        fileList.value = [];
        fileListCopy.value = [];
        dialogVisible.value = false;
        submitLoading.value = false;
        if (modalType.value == "add") {
          getList();
        } else {
          getRecordList();
        }
        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 handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileListCopy.value.push({
    id: res.id,
    fileName: res.fileName,
    path: res.fileUrl,
    url: res.fileUrl,
    uid: file.uid,
  });
};

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, isChange) => {
  proxy.post("/areaInfo/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (isChange) {
        formData.data.provinceId = "";
        formData.data.cityId = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (isChange) {
        formData.data.cityId = "";
      }
    } 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 afterSalesType = ref([]);
const afterSalesStatus = ref([]);

const getDict = () => {
  proxy.getDict(["after_sale_type", "after_sale_status"]).then((res) => {
    afterSalesType.value = res["after_sale_type"];
    configData[0][0].data = afterSalesType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    selectConfig[0].data = afterSalesType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    afterSalesStatus.value = res["after_sale_status"];
    configData[1][0].data = afterSalesStatus.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    selectConfig[1].data = afterSalesStatus.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getCityData("0");
getList();
getDict();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>