<template>
  <div class="project-setPlan" v-loading="loading">
    <div class="project-setPlan-main">
      <div class="project-setPlan-title">商品要求</div>
      <div class="project-setPlan-ask-table">
        <template v-if="ladder">
          <el-table
            :data="ladder"
            :size="'mini'"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column label="要求编码" prop="pgNo" width="180px" />

            <el-table-column prop="good_type" label="商品类型" width="80px">
              <template slot-scope="scope">
                <el-tag
                  :size="'mini'"
                  v-text="
                    (
                      statusOptions.find(
                        (item) => item.value == scope.row.good_type
                      ) || {}
                    ).label || '--'
                  "
                ></el-tag
              ></template>
            </el-table-column>
            <el-table-column prop="budget_price" label="预算单价" width="110" />
            <el-table-column prop="num" label="购买数量" width="110" />
            <el-table-column prop="cat_name" label="商品分类" />
            <el-table-column prop="good_img" label="图片" width="50">
              <template slot-scope="scope">
                <div
                  v-if="scope.row.good_img"
                  style="width: 20px; height: 20px"
                  class="hover"
                  v-viewer
                >
                  <img
                    :src="scope.row.good_img"
                    style="display: inline-block; width: 100%; height: 100%"
                    alt=""
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="good_name" label="商品名称" />
          </el-table>
        </template>
      </div>
      <div class="project-setPlan-title">客户意向商品</div>
      <div class="project-setPlan-backGood-table">
        <el-table
          :data="tableData"
          :size="'mini'"
          border
          stripe
          ref="multipleTable"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="40"
            v-if="table_type === 'add'"
          >
          </el-table-column>
          <el-table-column
            prop="pgNo"
            label="要求编码"
            width="180px"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sale_price"
            label="销售单价"
            width="110"
            show-overflow-tooltip
          />
          <el-table-column
            prop="num"
            label="购买数量"
            width="110"
            show-overflow-tooltip
          />
          <el-table-column
            prop="good_img"
            label="图片"
            width="50"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div
                v-if="scope.row.good_img"
                style="width: 20px; height: 20px"
                class="hover"
                v-viewer
              >
                <img
                  :src="scope.row.good_img"
                  style="display: inline-block; width: 100%; height: 100%"
                  alt=""
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="good_name"
            label="商品名称"
            show-overflow-tooltip
          />
          <el-table-column
            prop="class_cat"
            label="商品分类"
            show-overflow-tooltip
          />
          <el-table-column prop="model" label="规格" show-overflow-tooltip />
          <el-table-column
            prop="expiry_day"
            label="信息有效期"
            width="85"
            show-overflow-tooltip
          />
          <el-table-column
            prop="work_day"
            label="制作工期"
            width="85"
            show-overflow-tooltip
          />
          <el-table-column
            prop="delivery_day"
            label="物流时间"
            width="85"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <div class="project-setPlan-title">
        方案制定
        <span v-if="plan_show && table_type === 'list'"
          >方案总金额：{{ plan_show.sale_total }}元</span
        >
        <el-button-group
          :size="'mini'"
          class="fr"
          v-if="table_type === 'list'"
          style="margin: 8px 0 0 0"
        >
          <el-button
            class="fr"
            type="primary"
            :size="'mini'"
            :disabled="index === 0"
            v-if="total !== 0"
            icon="el-icon-arrow-left"
            @click="index--, change_plan()"
          ></el-button>
          <el-button
            type="primary"
            class="fr"
            v-if="total !== 0"
            :size="'mini'"
            style="height: 29px"
            >方案共{{ index + 1 }}/{{ total }}</el-button
          >
          <el-button
            type="primary"
            class="fr"
            :disabled="index + 1 === total"
            v-if="total !== 0"
            @click="index++, change_plan()"
            :size="'mini'"
            ><i class="el-icon-arrow-right el-icon--right" :size="'mini'"></i
          ></el-button>
          <el-button
            type="primary"
            class="fr"
            v-if="
              powers &&
              powers.length > 0 &&
              powers.some((item) => item == '064') &&
              status == '3'
            "
            @click="add_plan"
            icon="el-icon-circle-plus-outline"
            :size="'mini'"
            >添加方案
          </el-button>
        </el-button-group>
        <el-button-group
          :size="'mini'"
          class="fr"
          v-else-if="table_type === 'add'"
          style="margin: 8px 0 0 0"
        >
          <el-button
            class="fr"
            type="primary"
            :size="'mini'"
            icon="el-icon-arrow-left"
            @click="back_list"
            >返回列表</el-button
          >
          <el-button type="primary" class="fr" @click="save_plan" :size="'mini'"
            >保存方案<i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </el-button-group>
      </div>
      <div class="project-setPlan-backGood-table" v-if="plan_show && tableList">
        <div class="table-row">
          <ul class="table-header">
            <li v-for="head in headCol" :key="head.label">{{ head.label }}</li>
          </ul>
          <template v-if="tableList.length > 0">
            {{ tableList[0] }}
            <ul class="table-body" v-for="item in tableList" :key="item.planNo">
              <li v-for="head in headCol" :key="head.prop + item.planNo">
                <template v-if="head.prop === 'sale_price' && head._slot_">
                  <digital-input
                    v-if="table_type === 'add'"
                    :values="item[head.prop]"
                    :placeholder="'售价'"
                    :min="0"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="moq_num_change($event, 1)"
                  />
                </template>
                <template v-if="head.prop === 'good_img' && head._slot_">
                  <div
                    v-if="item[head.prop]"
                    style="width: 20px; height: 20px"
                    class="hover"
                    v-viewer
                  >
                    <img
                      :src="item[head.prop]"
                      style="display: inline-block; width: 100%; height: 100%"
                      alt=""
                    />
                  </div>
                </template>
                <template v-else>
                  <span>{{ item[head.prop] }}</span>
                  <span v-if="head.unit">{{ head.unit }}</span>
                </template>
              </li>
            </ul>
          </template>
          <div v-else class="table-no-data">暂无数据！</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/project";
import resToken from "@/mixins/resToken";
import columnsForm from "./columnsForm";
export default {
  name: "setPlan",
  props: ["showModel", "sitem", "id", "type"],
  mixins: [resToken],
  computed: {
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "projectDetail"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  watch: {
    // showModel: function (val) {
    //   this.showModelThis = val;
    //   if (val) {
    //     this.initForm();
    //   }
    // },
    // showModelThis(val) {
    //   if (!val) {
    //     this.$emit("cancel");
    //   }
    // },
  },
  data() {
    return {
      headCol: [
        {
          prop: "pgNo",
          label: "要求编码",
          _slot_: "status",
        },
        {
          prop: "origin_price",
          label: "系统售价单价",
          unit: "元",
        },
        {
          prop: "sale_price",
          label: "当前销售单价",
          _slot_: false,
          unit: "元",
        },
        {
          prop: "num",
          label: "购买数量",
        },
        {
          prop: "good_img",
          label: "图片",
          _slot_: true,
        },
        {
          prop: "good_name",
          label: "商品名称",
        },
        {
          prop: "class_cat",
          label: "商品分类",
        },
        {
          prop: "model",
          label: "规格",
        },
        {
          prop: "expiry_day",
          label: "信息有效期",
          unit: "天",
        },
        {
          prop: "work_day",
          label: "制作工期",
          unit: "天",
        },
        {
          prop: "delivery_day",
          label: "物流时间",
          unit: "天",
        },
      ],
      showModel: false,
      searchItem: {},
      loading: false,
      allPlanList: [],
      ladder: [],
      tableList: [],
      index: 0,
      total: 0,
      table_type: "list",
      //   allList: [],
      projectNo: "",
      status: "",
      statusOptions: [
        { value: "1", label: "竞品" },
        { value: "2", label: "竞聘" },
      ],
      table: {
        stripe: true,
        border: true,
        // _defaultHeader_: ["setcol"],
      },
      // 表格 - 列参数
      columns: columnsForm,
      tableData: [],
      multipleSelection: [],
      plan_show: {
        sale_total: "0",
        feedback: [],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    //初始化整个组件
    async initForm() {
      // this.loading = true;
      await this.initListData();
      await this.back_list();
      this.loading = false;
    },
    async resetFormData() {
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.loading = true;
      this.tableData = [];
      await this.searchList();
    },
    async back_list() {
      this.table_type = "list";
      await this.get_plan("1");
    },
    add_plan() {
      this.table_type = "add";
      this.plan_show = {
        sale_total: "0",
        feedback: [],
      };
    },
    moq_num_change(e, index) {
      this.plan_show.feedback[index].sale_price = e + "";
      this.$set(
        this.plan_show.feedback[index],
        index,
        this.plan_show.feedback[index]
      );
    },
    //初始化整个组件
    async initListData() {
      console.log(this.sitem);
      const { projectNo, ladder, status } = this.sitem;
      this.status = status;
      this.projectNo = projectNo;
      this.ladder =
        ladder && ladder.length > 0 ? JSON.parse(JSON.stringify(ladder)) : [];
      this.pageInfo = {
        size: 100,
        curr: 1,
        total: 0,
      };
      this.tableData = [];
      await this.searchList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;

      let list = JSON.parse(JSON.stringify(this.plan_show.feedback));
      this.plan_show = {
        sale_total: "0",
        feedback: [],
      };
      this.multipleSelection.forEach((a, i) => {
        let fi = list.findIndex((b) => a.id === b.id && b.pgNo === a.pgNo);
        if (fi !== -1) {
          this.plan_show.feedback.push(list[fi]);
        } else {
          this.plan_show.feedback.push(this.multipleSelection[i]);
        }
      });
      this.plan_show.feedback.map((e) => {
        e.sale_price = "0";
        return e;
      });
    },

    async searchList() {
      const { size, curr } = this.pageInfo;
      // this.loading = true;
      let model = {
        page: curr,
        size: size,
        zxNo: "",
        infoNo: "",
        bidNo: "",
        status: "1",
        pgNo: "",
        projectNo: this.projectNo,
      };
      const { code, data } = await asyncRequest.back_good_list(model);
      if (code === 0) {
        const { list, count } = data;
        this.tableData = list;
        this.tableData.map((v) => {
          v.class_cat = "";
          if (v.can && v.can.length > 0) {
            v.can.forEach((x, i) => {
              v.class_cat += i === 0 ? x.name : "/" + x.name;
            });
          }
          return v;
        });
        this.pageInfo.total = Number(count);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      // this.loading = false;
    },
    //保存方案
    async save_plan() {
      if (!this.loading) {
        const { feedback } = this.plan_show;
        console.log(feedback);
        let list = feedback;
        let isok = true;
        list.forEach((a) => {
          let findex = list.findIndex(
            (b) => b.pgNo === a.pgNo && a.id !== b.id
          );
          if (findex !== -1) {
            isok = false;
          }
        });
        if (!isok) {
          this.$message.warning("一种商品要求只能选择一种商品！");
          return;
        }
        let isall = true;
        this.ladder.forEach((a) => {
          let to = 0;
          list.forEach((b) => {
            if (a.pgNo === b.pgNo) {
              to++;
            }
          });
          if (to !== 1) {
            isall = false;
          }
        });
        if (!isall) {
          this.$message.warning("方案必须涵盖全部商品要求！");
          return;
        }
        this.loading = true;
        let model = {
          feedback: [],
          projectNo: this.projectNo,
        };

        list.forEach((e) => {
          let si = {
            feedid: e.id,
            sale_price: e.sale_price,
          };
          model.feedback.push(si);
        });
        const { code, data, message } = await asyncRequest.project_make_plan(
          model
        );
        if (code === 0) {
          await this.back_list();
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
        this.loading = false;
      }
    },
    //获取全部方案
    async get_plan(type) {
      let model = {
        projectNo: this.projectNo,
      };
      const { code, data, message } = await asyncRequest.get_project_plan(
        model
      );
      if (code === 0) {
        this.allPlanList =
          data && data.length > 0 ? JSON.parse(JSON.stringify(data)) : [];
        this.total = this.allPlanList.length;

        if (type) {
          await this.change_plan("1");
        }
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    //切换当前展示的方案
    async change_plan(type) {
      this.table_type = "list";
      this.plan_show = {
        sale_total: "0",
        feedback: [],
      };
      if (type) {
        this.index = 0;
      }
      console.log(this.allPlanList[this.index]);
      const { sale_total, feedback, planNo } = JSON.parse(
        JSON.stringify(this.allPlanList[this.index])
      );
      this.plan_show = {
        sale_total: sale_total,
        feedback:
          feedback && feedback.length > 0
            ? JSON.parse(JSON.stringify(feedback))
            : [],
      };
      // for (let i = 0; i < this.plan_show.feedback.length; i++) {
      //   this.plan_show.feedback[i].planNo = planNo;
      // }
      this.tableList = JSON.parse(JSON.stringify(this.plan_show.feedback));
      // for (let i = 0; i < this.plan_show.feedback.length; i++) {
      //   this.$set(this.plan_show.feedback[i], i, this.plan_show.feedback[i]);
      // }
    },
  },
};
</script>

   <style lang="scss" scoped>
.project-setPlan {
  box-sizing: border-box;
  width: 100%;

  .project-setPlan-main {
    padding: 2px 16px 16px 16px;
    // background: #fefefe;
    border-radius: 5px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    margin: 0 0 16px 0;
    .project-setPlan-title {
      height: 48px;
      line-height: 48px;
      color: #676767;
    }
  }
  .table-row {
    width: 100%;
    border-top: 1px solid #dfe6ec;
    .table-header,
    .table-body {
      display: flex;
      //
      border-left: 1px solid #dfe6ec;
      li {
        width: 110px;
        font-weight: 500;
        font-size: 12px;
        padding: 10px;
        overflow: hidden;
        box-sizing: border-box;
        border-right: 1px solid #dfe6ec;
        border-bottom: 1px solid #dfe6ec;
        &:nth-child(1) {
          width: 180px;
        }
      }
    }
    .table-header {
      li {
        color: #909399;
      }
    }
    .table-body {
      li {
        color: #606266;
      }
    }
  }
}
</style>
