<template>
  <div>
    <div v-if="isMerchant">
      <obj-table-plus
        style="height: calc(100vh - 132px)"
        ref="oTable"
        mode="flex"
        :tableCols="tableCols"
        v-model="dataList"
        @query="queryList"
        :enableAutoQuery="false"
      >
        <template slot="flexEmpty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <div slot="tableTop" class="mb-2">
          <el-form inline>
            <el-form-item label="模板名称：">
              <el-input
                placeholder="请输入模板名称"
                v-model="searchForm.name"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="marketList.length > 0" label="摊铺">
              <el-select v-model="searchForm.linkId" placeholder="请选择摊铺">
                <el-option
                  v-for="item in marketList"
                  :key="item.marketId"
                  :label="item.marketName"
                  :value="item.marketId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-button type="primary" @click="$refs.oTable.reload()"
              >搜索</el-button
            >
            <el-button type="primary" @click="Reset">重置</el-button>
          </el-form>
          <el-button type="primary" @click="addFareTemplate"
            >添加运费模板</el-button
          >
        </div>
      </obj-table-plus>
      <add-template
        ref="addTemplate"
        @refresh="$refs.oTable.refresh()"
      ></add-template>
    </div>
    <div style="height: calc(100vh - 200px)" v-else>
      <el-empty :image-size="200" description="请先去完成认证"></el-empty>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { Message } from "element-ui";
import addTemplate from './popup/add-template.vue'
export default {
  components: { addTemplate },
  data() {
    return {
      dataList: [],
      searchForm: {
        name: '',
        linkId: ''
      }
    }
  },
  created() {
    if (
      JSON.parse(sessionStorage.getItem('userInfo')).role === 'ROLE_MERCHANT'
    ) {
      this.searchForm = {
        name: '',
        linkId: this.shopId
      }
    } else {
      this.searchForm = {
        name: '',
        linkId: this.marketId ? this.marketId : this.shopId
      }
    }

    this.$nextTick(() => {
      this.$refs.oTable.reload()
    })
  },
  methods: {
    queryList(pageNo, pageSize) {
      this.$api.mer_admin
        .getShippingTemplatePage({
          pageNumber: pageNo,
          pageSize: pageSize,
          ...this.searchForm
        })
        .then(res => {
          console.log(res)
          this.$refs.oTable.complete(
            res.data.data.data,
            Number(res.data.data.total)
          )
        })
        .catch(err => {
          this.$refs.oTable.complete(false)
        })
    },
    Reset() {
      if (
        JSON.parse(sessionStorage.getItem('userInfo')).role === 'ROLE_MERCHANT'
      ) {
        this.searchForm = {
          name: '',
          linkId: this.shopId
        }
      } else {
        this.searchForm = {
          name: '',
          linkId: this.marketId ? this.marketId : this.shopId
        }
      }
      this.$refs.oTable.reload()
    },
    addFareTemplate() {
      this.$refs.addTemplate.toggle().add(this.searchForm.linkId)
    }
  },
  computed: {
    tableCols() {
      return [
        {
          type: 'jsx',
          render: row => {
            console.log(row)
            this.$api.mer_admin.getShippingTemplateInfo(row.id).then(res => {
              console.log(res)
              console.log('row.tableData', row.tableData)
              if (!row.tableData) {
                if (res.data.data.shippingTemplatesRegionResultList) {
                  this.$set(
                    row,
                    'tableData',
                    res.data.data.shippingTemplatesRegionResultList.map(
                      item => {
                        item.cityCodes = item.cityCodes?.split(',')
                        console.log('item.cityCodes', item.cityCodes)

                        return item
                      }
                    )
                  )
                } else {
                  //包邮，假数据写死
                  this.$set(row, 'tableData', [
                    {
                      cityCodes: '0',
                      first: '1',
                      firstPrice: '0.00',
                      renewal: '1',
                      renewalPrice: '0.00'
                    }
                  ])
                }
                if (res.data.data.shippingTemplatesConditionResultList) {
                  this.$set(
                    row,
                    'bytableData',
                    res.data.data.shippingTemplatesConditionResultList.map(
                      item => {
                        item.cityCodes = item.cityCodes?.split(',')
                        console.log('item.cityCodes', item.cityCodes)
                        if (
                          typeof item.price == "number" &&
                          typeof item.number == "number"
                        ) {
                          item.conditionType = "件数+金额";
                        } else if (
                          typeof item.price == "number" &&
                          typeof item.number != "number"
                        ) {
                          item.conditionType = "金额";
                        } else if (
                          typeof item.price != "number" &&
                          typeof item.number == "number"
                        ) {
                          item.conditionType = "件数";
                        }
                        return item
                      }
                    )
                  )
                } else {
                  //包邮，假数据写死
                  this.$set(row, 'bytableData', [
                    {
                      cityCodes: '0',
                      createTime: null,
                      groups: 1,
                      id: '',
                      number: 1.0,
                      price: null,
                      tempId: '',
                      title: '',
                      updateTime: null,
                      value: null
                    }
                  ])
                }
              }
            })
            const findLabelsByCode = (tree, codes) => {
              // 记录找到的路径
              let paths = []

              if (codes == '0') {
                return ['中国']
              }

              // 在树中搜索节点的递归函数
              function searchTree(node, currentPath) {
                // 将当前节点添加到路径中
                currentPath.push(node.name)

                // 如果当前节点的 code 在 codes 数组中，记录路径
                if (codes.includes(node.code)) {
                  paths.push([...currentPath]) // 深拷贝当前路径
                }

                // 如果有子节点，继续递归查找
                if (node.children) {
                  for (let child of node.children) {
                    searchTree(child, currentPath)
                  }
                }

                // 回溯，移除当前节点
                currentPath.pop()
              }

              // 对树的每个顶层节点调用 searchTree
              for (let node of tree) {
                searchTree(node, [])
              }

              // 将所有找到的路径合并成字符串返回
              return paths.map(path => <p>{path.join('/')}</p>)
            }

            const appointMapper = {
              0: '（全国包邮）',
              1: '（部分包邮）',
              2: '（自定义运费）'
            }

            const edit = () => {
              this.$api.mer_admin.getShippingTemplateInfo(row.id).then(res => {
                console.log(res)
                this.$refs.addTemplate.toggle().update(res.data.data)
              })
            }
            const copy = () => {
              this.$api.mer_admin.getShippingTemplateInfo(row.id).then(res => {
                console.log(res)
                this.$refs.addTemplate.toggle().copy(res.data.data)
              })
            }
            const remove = () => {
              this.$api.mer_admin.removeShippingTemplate(row.id).then(res => {
                this.$refs.oTable.refresh()
              })
            }
            const groupMapper = {
              1: {
                first: '首件（个）',
                renewal: '续件（个）'
              },
              2: {
                first: '首重（kg）',
                renewal: '续重（kg）'
              }
            }
            //打开弹窗预览
            const openPreview = str => {
              this.$confirm(
                <div style="max-height:50vh;overflow-y:auto;line-height:1.5rem;">
                  {str}
                </div>,
                '详情',
                {
                  showCancelButton: false,
                  confirmButtonText: '好的'
                }
              )
            }
            return (
              <div class="mb-5">
                <div class="flex justify-between items-center bg-gray-100 px-4">
                  <div>
                    {row.name}
                    {appointMapper[row.appoint]}
                  </div>
                  <div class="flex justify-between items-center">
                    <div class="mr-5">最后编辑时间：{row.updateTime}</div>
                    <div>
                      <el-button type="text" onClick={copy}>
                        复制模板
                      </el-button>
                      <el-button type="text" onClick={edit}>
                        修改
                      </el-button>
                      <el-popconfirm
                        class="ml-2"
                        title="确认删除模板？"
                        onConfirm={remove}
                      >
                        <el-button type="text" slot="reference">
                          删除
                        </el-button>
                      </el-popconfirm>
                    </div>
                  </div>
                </div>
                <vxe-table
                  max-height="300"
                  border
                  align="center"
                  show-overflow
                  data={row.tableData}
                >
                  <vxe-column
                    width="180px"
                    field="cityCodes"
                    title="运送到"
                    scopedSlots={{
                      default: scope => {
                        console.log('scope', scope)
                        return (
                          <span
                            class="cursor-pointer"
                            onClick={() => {
                              openPreview(
                                findLabelsByCode(
                                  this.$api.mer_admin.getCityOptions(),
                                  scope.row.cityCodes
                                )
                              )
                            }}
                          >
                            {findLabelsByCode(
                              this.$api.mer_admin.getCityOptions(),
                              scope.row.cityCodes
                            )}
                          </span>
                        )
                      }
                    }}
                  ></vxe-column>
                  <vxe-column
                    width="200px"
                    field="first"
                    title={groupMapper[row.groups].first}
                  ></vxe-column>
                  <vxe-column
                    width="200px"
                    field="firstPrice"
                    title="首费（元）"
                  ></vxe-column>
                  <vxe-column
                    width="200px"
                    field="renewal"
                    title={groupMapper[row.groups].renewal}
                  ></vxe-column>
                  <vxe-column
                    width="200px"
                    field="renewalPrice"
                    title="运费（元）"
                  ></vxe-column>
                </vxe-table>
                <vxe-table
                  max-height="300"
                  border
                  align="center"
                  show-overflow
                  data={row.bytableData}
                >
                  <vxe-column
                    width="180px"
                    field="cityCodes"
                    title="运送到"
                    scopedSlots={{
                      default: scope => {
                        console.log('scope', scope)
                        return (
                          <span
                            class="cursor-pointer"
                            onClick={() => {
                              openPreview(
                                findLabelsByCode(
                                  this.$api.mer_admin.getCityOptions(),
                                  scope.row.cityCodes
                                )
                              )
                            }}
                          >
                            {findLabelsByCode(
                              this.$api.mer_admin.getCityOptions(),
                              scope.row.cityCodes
                            )}
                          </span>
                        )
                      }
                    }}
                  ></vxe-column>
                  <vxe-column
                    field="conditionType"
                    title={'包邮条件'}
                  ></vxe-column>
                  <vxe-column
                    field="number"
                    title={'包邮件数'}
                  ></vxe-column>
                  <vxe-column
                    field="price"
                    title={'包邮价格'}
                  ></vxe-column>
                </vxe-table>
              </div>
            )
          }
        }
      ]
    },
    ...mapState('userData', [
      'isMerchant',
      'marketList',
      'storeList',
      'marketId',
      'shopId'
    ])
  }
}
</script>

<style lang="scss" scoped></style>
