<template>
  <ele-modal
    title="选择商品"
    custom-class="ele-dialog-form long-dialog-form"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
    :maxable="true"
    :resizable="true"
  >
    <div class="ele-body">
      <el-card shadow="never" v-loading="loading">
        <ele-split-layout
          width="210px"
          allow-collapse
          :right-style="{ overflow: 'hidden' }"
        >
          <div>
            <div class="ele-border-lighter sys-organization-list">
              <AssetTree
                @handleNodeClick="handleNodeClick"
                id="1789827921908150274"
                :isIds="false"
                :isFirstRefreshTable="false"
                ref="treeList"
              />
            </div>
          </div>
          <template v-slot:content>
            <div
              class="ele-border-lighter form-content"
              v-loading="loading"
            ></div>
            <PriceSearch @search="reload"> </PriceSearch>
            <!-- 数据表格 -->
            <ele-pro-table
              ref="table"
              :columns="columns"
              :datasource="datasource"
              height="calc(100vh - 500px)"
              tool-class="ele-toolbar-form"
              :page-size="20"
              :selection.sync="selection"
              @cell-click="cellClick"
              row-key="id"
              v-if="visible"
            >
              <!-- 展开列 -->
              <template v-slot:expand="{ row }">
                <el-form
                  v-for="item in row.goodsPriceList"
                  :key="item.id"
                  label-width="100px"
                  class="el-form-box"
                >
                  <el-row class="price-info">
                    <el-col :span="3"
                      ><el-form-item label="价格类型：">
                        {{ getDictValue('商品价格类型', item.priceType) }}
                      </el-form-item></el-col
                    >
                    <el-col :span="3"
                      ><el-form-item label="含税单价：">{{
                        item.unitPrice
                      }}</el-form-item></el-col
                    >
                    <el-col :span="3"
                      ><el-form-item label="税率："
                        >{{ item.taxRate }}%</el-form-item
                      ></el-col
                    >
                    <el-col :span="3"
                      ><el-form-item label="不含税单价：">{{
                        item.excludeTaxPrice
                      }}</el-form-item></el-col
                    >

                    <el-col :span="3">
                      <el-form-item label="">
                        <el-link
                          @click="openHistoricalprice(item)"
                          type="primary"
                          :underline="false"
                          icon="el-icon-sort-edit"
                        >
                          历史价格
                        </el-link>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>
              <!-- 列详情 -->
              <template v-slot:goodsName="{ row }">
                <el-link
                  type="primary"
                  :underline="false"
                  @click="openEdit('view', row)"
                >
                  {{ row.goodsName }}</el-link
                >
              </template>

              <!-- 商品图片 -->
              <template v-slot:imagesPaths="{ row }">
                <el-image
                  v-if="row.imagesPaths"
                  style="width: 50px; height: 50px"
                  fit="cover"
                  :src="
                    locationUrl +
                    '/api/main/file/getFile?objectName=' +
                    row.imagesPaths.split(',')[0]
                  "
                  :preview-src-list="
                    row.imagesPaths
                      .split(',')
                      .map(
                        (url) =>
                          locationUrl +
                          '/api/main/file/getFile?objectName=' +
                          url
                      )
                  "
                />
              </template>
              <!-- 表头工具栏 -->
              <template v-slot:action="{ row }">
                <!-- <el-radio class="radio" v-model="radio" :label="row.code"></el-radio> -->
                <el-radio class="radio" v-model="radio" :label="row.id">
                  <i></i>
                </el-radio>
              </template>
            </ele-pro-table>
          </template>
        </ele-split-layout>
      </el-card>

      <AddDialog ref="addContactDialogRef" @done="reload"></AddDialog>
      <EditPriceDialog ref="editPriceDialogRef" @done="reload">
      </EditPriceDialog>
      <HistoricalpriceDialog
        ref="historicalpriceDialogRef"
        @done="reload"
      ></HistoricalpriceDialog>
    </div>

    <div class="btns" slot="footer">
      <el-button type="primary" size="small" @click="selected">选择</el-button>
      <el-button size="small" @click="visible = false">关闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import HistoricalpriceDialog from './historicalpriceDialog.vue';
  import EditPriceDialog from './editPriceDialog.vue';
  import AssetTree from '@/components/AssetTree';
  import PriceSearch from './priceSearch.vue';
  import AddDialog from './addDialog.vue';
  import { getList } from '@/api/goodsManage/index';
  import dictMixins from '@/mixins/dictMixins';
  import { reviewStatus } from '@/enum/dict';
  import { mapGetters } from 'vuex';
  import { getInventoryTotalAPI } from '@/api/wms';
  import { contactQueryByCategoryIdsAPI } from '@/api/saleManage/contact';

  export default {
    mixins: [dictMixins],
    components: {
      HistoricalpriceDialog,
      EditPriceDialog,
      AssetTree,
      PriceSearch,
      AddDialog
    },

    data() {
      return {
        locationUrl: window.location.origin,
        visible: false,
        loading: false,
        // 表格列配置
        currentIndex: '',
        current: null,
        radio: null,
        selection: [],
        curNodeData: {} //右侧菜单选择对象
      };
    },
    created() {
      this.requestDict('商品价格类型');
    },
    computed: {
      ...mapGetters(['user']),
      columns() {
        let data = null;
        if (this.currentIndex != -1) {
          data = {
            action: 'action',
            slot: 'action',
            align: 'center',
            label: '选择',
            reserveSelection: true
          };
        }
        if (this.currentIndex == -1) {
          data = {
            label: '选择',
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          };
        }

        return [
          data,

          {
            width: 45,
            type: 'expand',
            columnKey: 'expand',
            align: 'center',
            slot: 'expand'
          },
          {
            columnKey: 'index',
            type: 'index',
            width: 50,
            align: 'center',
            showOverflowTooltip: true,
            label: '序号'
          },
          {
            prop: 'goodsCode',
            label: '商品编码',
            align: 'center',
            showOverflowTooltip: true,
            sortable: true,
            width: 180
          },
          {
            prop: 'imagesPaths',
            label: '商品图片',
            align: 'center',
            slot: 'imagesPaths',
            width: 180
          },
          {
            prop: 'goodsName',
            label: '商品名称',
            align: 'center',
            slot: 'goodsName',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'categoryLevelName',
            label: '商品分类',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'categoryName',
            align: 'center',
            label: '产品名称',
            showOverflowTooltip: true,
            minWidth: 180
          },
          // {
          //   prop: '产品编码',
          //   label: '产品编码',
          //   align: 'center',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: '产品类型',
          //   label: '产品类型',
          //   align: 'center',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'priceType',
          //   label: '价格类型',
          //   slot: 'priceType',
          //   align: 'center',
          //   width: 120,
          //   formatter: (row, column) => {
          //     if (row.priceType) {
          //       return this.goodsTypeList.find((item) => item[row.priceType])?.[
          //         row.priceType
          //       ];
          //     }
          //   }
          // },
          // {
          //   prop: 'unitPrice',
          //   label: '含税单价',
          //   slot: 'unitPrice',
          //   align: 'center'
          // },
          // {
          //   prop: 'taxRate',
          //   slot: 'taxRate',
          //   label: '税率',
          //   align: 'center'
          // },
          // {
          //   prop: 'excludeTaxPrice',
          //   label: '不含税单价',
          //   slot: 'excludeTaxPrice',
          //   align: 'center'
          // },
          {
            prop: 'goodsStatus',
            align: 'center',
            width: 150,
            label: '状态',
            showOverflowTooltip: true,
            formatter: (row, column) => {
              return row.goodsStatus === 0
                ? '下架'
                : row.goodsStatus === 1
                ? '上架'
                : '';
            }
          },
          {
            prop: 'approvalStatus',
            label: '审核状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return reviewStatus[_row.approvalStatus];
            }
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          }
        ];
      }
    },
    methods: {
      open(index) {
        this.currentIndex = index;
        this.current = null;
        this.radio = null;
        this.selection = [];
        this.visible = true;
      },
      // 单击获取id
      cellClick(row) {
        if (this.currentIndex == -1) return;
        this.current = row;
        this.radio = row.id;
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        return getList({
          pageNum: page,
          size: limit,
          // goodsStatus:1,
          ...where
        });
      },
      handleNodeClick(data, node) {
        this.curNodeData = data;
        this.reload({ categoryLevelId: data.id });
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },
      async getSupplierObj(productList, queryName) {
        try {
          let categoryIds = productList
            .filter((item) => item.productId)
            .map((item) => item.productId);
          if (categoryIds.length > 0) {
            return await contactQueryByCategoryIdsAPI({
              categoryIds,
              isQueryEE: 1
            });
          } else {
            return Promise.resolve({});
          }
        } catch (e) {
          return Promise.resolve({});
        }
      },
      //历史价格
      openHistoricalprice(row) {
        this.$refs.historicalpriceDialogRef.open(row);
      },

      openEdit(type, row) {
        this.$refs.addContactDialogRef.open(type, row, this.curNodeData.id);
        this.$refs.addContactDialogRef.$refs.form &&
          this.$refs.addContactDialogRef.$refs.form.clearValidate();
      },

      openEditPrice(row) {
        this.$refs.editPriceDialogRef.open(row);
        this.$refs.editPriceDialogRef.$refs.form &&
          this.$refs.editPriceDialogRef.$refs.form.clearValidate();
      },
      async selected() {
        if (!this.selection.length&&!this.current) {
          return this.$message.warning('请至少选择一条数据');
        }
        let codeList = [];
        let list = this.currentIndex == -1 ? this.selection : [this.current];
        list=list.map(item=>{
         return {
              ...item.categoryInfo,
              goodsId:item.id,
              to:item.id,
              goodsPriceId:item.goodsPriceList[0]?.id,
              level:item.level,
              goodsPriceType:item.goodsPriceList[0]?.priceType,
              singlePrice:item.goodsPriceList[0]?.unitPrice,
              notaxSinglePrice:item.goodsPriceList[0]?.excludeTaxPrice,
              taxRate:item.goodsPriceList[0]?.taxRate,
          }
        })
        //获取仓库库存
        codeList = list.map((item) => item.code);
        let inventoryTotalList = await getInventoryTotalAPI(codeList);
        list.forEach((item) => {
          let find =
            inventoryTotalList.find((key) => key.code == item.code) || {};
          item.availableCountBase = find.availableCountBase;
        });
        let supplierList = await this.getSupplierObj(list);
        list.forEach((item) => {
          item['entrustedEnterpriseIdList'] = supplierList[item.id];
          if (supplierList[item.id]?.length === 1) {
            item['entrustedEnterpriseId'] = supplierList[item.id][0].id;
          }
        });
        this.$emit('changeParent', list, this.currentIndex);
        this.visible = false;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .tree_col {
    border: 1px solid #eee;
    padding: 10px 0;
    box-sizing: border-box;
    height: 500px;
    overflow: auto;
  }

  .table_col {
    padding-left: 10px;

    ::v-deep .el-table th.el-table__cell {
      background: #f2f2f2;
    }
  }

  .pagination {
    text-align: right;
    padding: 10px 0;
  }

  .btns {
    text-align: center;
    padding: 10px 0;
  }

  .topsearch {
    margin-bottom: 15px;
  }
</style>
