<template>
  <div class="pageIndexClass">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
             highlight-current-row :action-list="[
        ]" @get-list="getList">

      <template #code="{ item }">
        <div style="width: 100%">
          {{ item.code }}
          <!-- <span style="color: #409eff; cursor: pointer; word-break: break-all" @click="handleGenerate(item,true)">{{ item.code }}</span> -->
        </div>
      </template>

      <template #amount="{ item }">
        <div>
          <span style="padding-right: 4px">{{ item.currency }}</span>
          <span>{{ moneyFormat(item.amount, 2) }}</span>
        </div>
      </template>

      <template #status="{ item }">
        <div style="width: 100%">
          <span :style="{color: item.status ==88? 'red' :''}">{{dictValueLabel(item.status, statusData)}}</span>
        </div>
      </template>

      <template #follow="{ item }">
        <div style="width: 100%">
          <div style="width: 100%; display: flex">
            <template v-if="
                item.extQuotationFollowList &&
                item.extQuotationFollowList.length > 0
              ">
              <div class="tag" :style="
                  index > 2
                    ? 'display: none'
                    : ''
                " v-for="(record, index) in item.extQuotationFollowList" :key="record.id">
                <el-popover placement="bottom" :width="300" trigger="hover">
                  <template #default>
                    <div style="width: 100%">
                      <div style="color: #909399; margin: 8px 0">
                        跟进时间: {{ record.followTime }}
                      </div>
                      <div style="margin-top: 8px">
                        跟进说明: {{ record.remark }}
                      </div>
                    </div>
                  </template>
                  <template #reference>
                    <div>
                      <span v-if="record.followTime">{{
                        record.followTime.substr(0, 10)
                      }}</span>
                      <el-icon style="margin-left: 8px; transform: translateY(2px)" @click="deleteFollow(record)">
                        <DeleteFilled />
                      </el-icon>
                    </div>
                  </template>
                </el-popover>
              </div>
              <div class="tag" @click="clickMore(item)" v-if="item.extQuotationFollowList.length > 3">
                更多
              </div>
            </template>
          </div>
        </div>
      </template>

      <template #product="{ item }">
        <div style="width:100%;">
          <el-popover placement="bottom-start" title="" :width="300" trigger="hover">
            <div default>
              <div v-for="(product,index) in item.quotationProductList">
                {{index+1}}、{{product.productName}}
                <!-- <span v-if="index<item.quotationProductList.length-1">,</span> -->
              </div>
            </div>
            <template #reference>
              <div style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;cursor:pointer">
                <span v-for="(product,index) in item.quotationProductList">
                  {{product.productName}}
                  <span v-if="index<item.quotationProductList.length-1"> , </span>
                </span>
              </div>
            </template>
          </el-popover>
        </div>
      </template>

      <template #btn="{item}">
        <div style="width: 100%">
          <el-button type="primary" text v-debounce @click="handleFollow(item)">跟进</el-button>
          <el-button type="primary" text v-debounce @click="handleGenerate(item)">生成订单</el-button>
          <el-button type="danger" text v-debounce v-if="item.status !=0" @click="handleRepeal(item)">作废</el-button>
        </div>
      </template>
    </byTable>
    <el-dialog v-if="followDialog" v-model="followDialog" title="跟进" width="600" append-to-body>
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="formDom" v-loading="submitLoading">
      </byForm>
      <template #footer>
        <el-button @click="followDialog = false" size="default" v-debounce>关 闭</el-button>
        <el-button type="primary" @click="handleSubmit()" size="default" v-debounce>提 交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="跟进记录" v-if="openRecordMore" v-model="openRecordMore" width="800" destroy-on-close>
      <div>
        <el-button style="margin:0px 0px 20px 20px" type="primary" plain v-debounce @click="handleFollow(rowData)">添加跟进记录</el-button>
        <el-timeline>
          <el-timeline-item v-for="(record, index) in recordAllData" :key="record.id" :timestamp="record.followTime" hide-timestamp>
            <div>
              跟进时间：{{ record.followTime }}
            </div>
            <div style="word-wrap: break-word; margin: 8px 0">
              跟进说明：{{ record.remark }}
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="openRecordMore = false" size="default" v-debounce>关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import moment from "moment";
import byForm from "@/components/byForm/index";

const { proxy } = getCurrentInstance();
const accountList = ref([]);
const corporationList = ref([]);
const tradeMethods = ref([]);
const accountCurrency = ref([]);
const companyData = ref([]);
const statusData = ref([
  {
    label: "草稿",
    value: 0,
  },
  {
    label: "正常",
    value: 30,
  },
  {
    label: "作废",
    value: 88,
  },
]);
const quotationStatusData = ref([
  {
    label: "未报价",
    value: 0,
  },
  {
    label: "报价中",
    value: 1,
  },
  {
    label: "已报价",
    value: 2,
  },
]);
const typeData = ref([
  {
    label: "内销",
    value: "1",
  },
  {
    label: "外销",
    value: "2",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    type: "",
    quotationStatus: "",
    companyId: "",
    quotationTimeSta: "",
    quotationTimeEnd: "",
    beginTime: "",
    endTime: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "报价单状态",
      prop: "status",
      data: statusData.value,
    },
    {
      label: "报价单类型",
      prop: "type",
      data: typeData.value,
    },
    {
      type: "time",
      label: "报价时间",
      placeholder: "开始日期",
      prop: "quotationTimeSta",
      placeholderOne: "结束日期",
      propOne: "quotationTimeEnd",
    },
  ];
});

const config = computed(() => {
  return [
    {
      attrs: {
        label: "报价单号",
        slot: "code",
        width: 180,
      },
    },
    {
      attrs: {
        label: "报价单状态",
        slot: "status",
        width: 100,
      },
    },
    {
      attrs: {
        label: "报价单类型",
        prop: "type",
        width: 100,
      },
      render(val) {
        return proxy.dictValueLabel(val, typeData.value);
      },
    },
    {
      attrs: {
        label: "客户名称",
        prop: "buyCorporationName",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "报价金额",
        slot: "amount",
        width: 120,
      },
    },
    {
      attrs: {
        label: "报价时间",
        prop: "quotationTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "报价单产品",
        slot: "product",
        "min-width": 180,
      },
    },
    {
      attrs: {
        label: "跟进",
        slot: "follow",
        "min-width": 360,
      },
    },
    {
      attrs: {
        label: "操作",
        width: 200,
        slot: "btn",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

const getDict = () => {
  // proxy
  //   .post("/customer/selPage", {
  //     pageNum: 1,
  //     pageSize: 50,
  //   })
  //   .then((res) => {
  //     customerList.value = res.rows.map((x) => ({
  //       ...x,
  //       label: x.name,
  //       value: x.id,
  //     }));
  //   });

  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      keyword: "",
      tenantId: proxy.useUserStore().user.tenantId,
      type: 0,
    })
    .then((res) => {
      companyData.value = res.data.map((x) => ({
        ...x,
        label: x.deptName,
        value: x.deptId,
      }));
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/extQuotation/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const formDom = ref(null);
const followDialog = ref(false);
const submitLoading = ref(false);
const formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  disabled: false,
});

const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "跟进信息",
    },
    {
      type: "date",
      itemType: "datetime",
      prop: "followTime",
      label: "跟进时间",
      itemWidth: 100,
      disabled: false,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "remark",
      label: "跟进说明",
      itemWidth: 100,
      disabled: false,
    },
  ];
});
const rules = ref({
  followTime: [
    { required: true, message: "请选择跟进时间", trigger: "change" },
  ],
  remark: [{ required: true, message: "请输入跟进说明", trigger: "blur" }],
});

const handleFollow = (row) => {
  formData.data = {
    quotationId: row.id,
    followTime: moment().format("yyyy-MM-DD HH:mm:ss"),
    remark: "",
  };
  followDialog.value = true;
};

const handleSubmit = (type) => {
  formDom.value.handleSubmit(() => {
    submitLoading.value = true;
    proxy.post("/extQuotationFollow/add", formData.data).then(
      (res) => {
        proxy.msgTip("操作成功", 1);
        followDialog.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const deleteFollow = (record) => {
  proxy
    .msgConfirm()
    .then((res) => {
      proxy
        .post("/extQuotationFollow/delete", {
          id: record.id,
        })
        .then((res) => {
          proxy.msgTip("操作成功", 1);
          getList();
        });
    })
    .catch((err) => {});
};

const openRecordMore = ref(false);
const recordAllData = ref([]);
const rowData = ref({});
const clickMore = (row) => {
  rowData.value = row;
  recordAllData.value = proxy.deepClone(row.extQuotationFollowList);
  openRecordMore.value = true;
};

const handleGenerate = (row) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      priceSheetId: row.id,
      flowKey: "contract_flow",
      flowName: "销售合同审批流程",
      random: proxy.random(),
    },
  });
};

const handleRepeal = (row) => {
  proxy
    .msgConfirm()
    .then((res) => {
      proxy
        .post("/extQuotation/cancellation", {
          id: row.id,
        })
        .then((res) => {
          proxy.msgTip("操作成功", 1);
          getList();
        });
    })
    .catch((err) => {});
};
</script>

<style lang="scss" scoped>
.tag {
  line-height: 32px;
  margin-right: 8px;
  padding: 0 8px;
  background-color: #eeeeee;
  border-radius: 4px;
  cursor: pointer;
}
</style>