<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="155px"
              show-overflow-tooltip
            />

            <el-table-column
              prop="good_type"
              label="商品类型"
              width="80px"
              show-overflow-tooltip
            >
              <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"
              show-overflow-tooltip
            />
            <el-table-column
              prop="num"
              label="购买数量"
              width="110"
              show-overflow-tooltip
            />
            <el-table-column prop="cat_name" label="商品分类" 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>
        </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="155px"
            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="商品图片"
            min-width="168px"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.good_img && scope.row.good_img.length > 0">
                <img
                  v-for="(si, sii) in scope.row.good_img"
                  :key="si + sii"
                  :src="si"
                  class="hover fl"
                  style="
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    margin: 0 2px 0 0;
                  "
                  alt=""
                  v-viewer
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="good_name"
            label="商品名称"
            min-width="120"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.good_name }}</span>
              <span v-for="(si, sii) in scope.row.specinfo" :key="si.id + sii">
                {{ sii === 0 ? "_" : "-" }}{{ si.spec_name }}[{{ si.spec_value_name }}]
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="data_source"
            label="商品来源"
            width="85"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag
                :size="'mini'"
                :type="scope.row.data_source === '1' ? 'success' : ''"
                >{{ scope.row.data_source === "1" ? "平台商品" : "采反商品" }}</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column prop="class_cat" label="商品分类" show-overflow-tooltip />
          <el-table-column
            prop="expire_day"
            label="信息有效期"
            width="85"
            show-overflow-tooltip
          />
          <el-table-column
            prop="work_day"
            label="制作工期"
            width="70"
            show-overflow-tooltip
          />
          <el-table-column
            prop="delivery_day"
            label="物流时间"
            width="70"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <div class="project-setPlan-title">
        项目方案
        <span
          style="margin: 0 0 0 50px; font-size: 13px; color: #e4393c"
          v-if="total !== 0 && table_type === 'list'"
          >{{ plan_show.status === "1" ? "已选定" : "" }}方案总金额：{{
            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
            type="primary"
            class="fr"
            v-if="ppowers.some((i) => i == '3') && (status == '3' || status == '4')"
            @click="add_plan"
            icon="el-icon-circle-plus-outline"
            :size="'mini'"
            >添加方案
          </el-button>
          <el-button
            type="primary"
            class="fr"
            v-if="
              plan_show.status === '1' && ppowers.some((i) => i == '5') && status == '5'
            "
            @click="place_order"
            :size="'mini'"
            >项目下单<i class="el-icon-shopping-cart-2 el-icon--right"></i>
          </el-button>
          <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-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">
        <el-table
          :data="plan_show.feedback"
          :size="'mini'"
          border
          stripe
          :ref="'multipleTable' + index"
          style="width: 100%"
        >
          <el-table-column
            prop="pgNo"
            label="要求编码"
            width="155px"
            show-overflow-tooltip
          />
          <el-table-column
            prop="origin_sale_price"
            label="系统售价单价"
            width="110"
            show-overflow-tooltip
          />

          <el-table-column
            prop="new_sale_price"
            label="当前销售单价"
            width="110"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="table_type === 'add'">
                <digital-input
                  :values="scope.row.new_sale_price"
                  :placeholder="'售价'"
                  :min="0"
                  :newTime="scope.row.time_price"
                  :max="100000000000"
                  :position="'right'"
                  :precision="2"
                  :size="'mini'"
                  :controls="false"
                  :append="''"
                  @reschange="
                    moq_num_change($event, scope.$index, 'new_sale_price', 'time_price')
                  "
                />
              </div>
              <span v-else>{{ scope.row.new_sale_price || scope.row.sale_price }}元</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="origin_num"
            label="竞价数量"
            width="110"
            show-overflow-tooltip
          />
          <el-table-column prop="num" label="购买数量" width="110" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="table_type === 'add'">
                <digital-input
                  :values="scope.row.num"
                  :placeholder="'购买数量'"
                  :min="scope.row.origin_num"
                  :max="100000000000"
                  :position="'right'"
                  :precision="0"
                  :newTime="scope.row.time_num"
                  :size="'mini'"
                  :controls="false"
                  :append="''"
                  @reschange="moq_num_change($event, scope.$index, 'num', 'time_num')"
                />
              </div>
              <span v-else>{{ scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="data_source" label="商品来源" width="85">
            <template slot-scope="scope">
              <el-tag
                :size="'mini'"
                :type="scope.row.data_source === '1' ? 'success' : ''"
                >{{ scope.row.data_source === "1" ? "平台商品" : "采反商品" }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="good_img"
            label="商品图片"
            min-width="242px"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.good_img && scope.row.good_img.length > 0">
                <img
                  v-for="(si, sii) in scope.row.good_img"
                  :key="si + sii"
                  :src="si"
                  class="hover fl"
                  style="
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    margin: 0 2px 0 0;
                  "
                  alt=""
                  v-viewer
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="good_name"
            label="商品名称"
            min-width="120"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.good_name }}</span>
              <span v-for="(si, sii) in scope.row.specinfo" :key="si.id + sii">
                {{ sii === 0 ? "_" : "-" }}{{ si.spec_name }}[{{ si.spec_value_name }}]
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="class_cat" label="商品分类" show-overflow-tooltip />
          <!-- <el-table-column
            prop="expiry_day"
            label="信息有效期"
            width="85"
            show-overflow-tooltip
          />
          <el-table-column
            prop="work_day"
            label="制作工期"
            width="70"
            show-overflow-tooltip
          />
          <el-table-column
            prop="delivery_day"
            label="物流时间"
            width="70"
            show-overflow-tooltip
          /> -->
        </el-table>
      </div>
      <buy-good-modal
        :showModel="bayGoodShowModel"
        :sitem="bayGoodItem"
        @cancel="bayGoodShowModel = false"
        @refresh="(bayGoodShowModel = false), $emit('resGoodOk')"
      />
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/project";
import resToken from "@/mixins/resToken";
import columnsForm from "./columnsForm";
import buyGoodModal from "./buyGoodModal";
export default {
  name: "setPlan",
  props: ["showModel", "sitem", "id", "type", "newTime"],
  mixins: [resToken],
  components: {
    buyGoodModal,
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find((i) => i.menu_route == "projectDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "PRO") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  watch: {
    // showModel: function (val) {
    //   this.showModelThis = val;
    //   if (val) {
    //     this.initForm();
    //   }
    // },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  data() {
    return {
      showModel: false,
      searchItem: {},
      loading: false,
      allPlanList: [],
      bayGoodItem: {},
      bayGoodShowModel: false,
      ladder: [],
      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;
    },
    //项目下单
    place_order() {
      const { company, khName, platform_name, arrtime, project_name } = this.sitem;
      // console.log("aaaaaaaaaaaaaaa",this.sitem)
      this.bayGoodItem = JSON.parse(JSON.stringify(this.allPlanList[this.index]));
      this.bayGoodItem.in_company = company;
      this.bayGoodItem.in_khname = khName;
      this.bayGoodItem.in_platform_name = platform_name;
      this.bayGoodItem.in_arrival_time = arrtime;
      this.bayGoodItem.in_project_name = project_name;
      this.bayGoodShowModel = true;
    },
    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() {
      const { low_rate } = this.sitem;
      let r = low_rate ? low_rate : "0";
      if (r * 100 === 0) {
        this.$message.warning("暂无项目毛利率，不能制定方案！");
        return;
      }
      this.table_type = "add";
      this.plan_show = {
        sale_total: "0",
        feedback: [],
      };
    },
    moq_num_change(e, index, key, time) {
      this.plan_show.feedback[index][key] = e + "";
      if (time) {
        this.plan_show.feedback[index][time] = new Date().valueOf;
      }

      this.$set(this.plan_show.feedback, 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 = 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) => {
        a.origin_sale_price = a.sale_price;
        a.new_sale_price = a.sale_price;
        console.log(a.origin_sale_price, a.sale_price);

        let fi = list.findIndex((b) => a.id === b.id && b.pgNo === a.pgNo);
        if (fi !== -1) {
          this.plan_show.feedback.push(JSON.parse(JSON.stringify(list[fi])));
        } else {
          this.plan_show.feedback.push(
            JSON.parse(JSON.stringify(this.multipleSelection[i]))
          );
        }
      });
      this.plan_show.feedback.map((e) => {
        e.origin_num = e.num;
        e.time_price = "";
        e.time_num = "";
        return e;
      });

      console.log(this.plan_show);
      setTimeout(() => {
        this.plan_show.feedback.forEach((a, index) => {
          a.time_price = new Date().valueOf();
          a.time_num = new Date().valueOf();
          this.$set(this.plan_show.feedback, index, this.plan_show.feedback[index]);
        });
        console.log(this.plan_show);
      }, 100);
    },

    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;
            });
          }
          if (v.good_img) {
            v.good_img =
              Object.prototype.toString.call(v.good_img) === "[object Array]"
                ? v.good_img
                : (v.good_img || "").split(",");
          }
          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;
        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.new_sale_price,
            good_num: e.num,
          };
          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 = JSON.parse(JSON.stringify(data));
        this.total = this.allPlanList.length;
        if (type && this.allPlanList.length > 0) {
          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",
        status: "0",
        feedback: [],
      };
      if (type) {
        this.index = 0;
      }
      if (this.status === "4") {
        this.allPlanList.forEach((a, ai) => {
          if (a.status === "1") {
            this.index = ai;
          }
        });
      }
      const { sale_total, feedback, status } = JSON.parse(
        JSON.stringify(this.allPlanList[this.index])
      );
      this.plan_show = {
        sale_total: sale_total,
        status: status,
        feedback: JSON.parse(JSON.stringify(feedback)),
      };
      this.plan_show.feedback.map((v) => {
        v.class_cat = "";
        if (v.cat_info && v.cat_info.length > 0) {
          v.cat_info.forEach((x, i) => {
            v.class_cat += i === 0 ? x.name : "_" + x.name;
          });
        }
        if (v.good_img) {
          v.good_img =
            Object.prototype.toString.call(v.good_img) === "[object Array]"
              ? v.good_img
              : (v.good_img || "").split(",");
        }
        return v;
      });

      console.log(this.plan_show);
      for (let i = 0; i < this.plan_show.feedback.length; i++) {
        this.$set(this.plan_show.feedback, 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;
    }
  }
}
</style>
