<template>
  <el-form
    ref="ruleForm"
    :loading="loading"
    :model="ruleForm"
    status-icon
    :size="'mini'"
    :rules="rulesThis"
    label-width="110px"
    style="width: 100%"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="销售方" prop="companyNo" class="clear">
          <search-work-company
            :value="ruleForm.companyNo"
            :placeholder="'销售方公司'"
            :disabled="type === 'view'"
            :size="'mini'"
            :isDetail="type === 'view'"
            @searchChange="company_idsearchChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="购买方公司" prop="khNo" class="clear">
          <search-customer
            :value="ruleForm.khNo"
            :names="ruleForm.customer_name"
            :placeholder="'购买方公司'"
            :size="'mini'"
            @searchChange="customerChange"
            :disabled="type === 'view'"
            :is-detail="type === 'view'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属平台" prop="platform_code" class="clear">
          <search-terrace
            :value="ruleForm.platform_code"
            :disabled="type === 'view'"
            :size="'mini'"
            :is_show="'1'"
            :isDetail="type === 'view'"
            :names="platform_code_name"
            :placeholder="'所属平台'"
            @searchChange="platform_code_codesearchChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="竞价截止时间" prop="endtime" class="clear">
          <el-date-picker
            v-model="ruleForm.endtime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            :picker-options="pickerOptions"
            placeholder="竞价截止时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="竞价类型" prop="is_project" class="clear">
          <el-select
            v-model="ruleForm.is_project"
            style="width: 100%"
            :disabled="false"
            placeholder="竞价类型"
            @change="is_project_change"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目名称" prop="projectNo" class="clear">
          <el-select
            v-model="ruleForm.projectNo"
            multiple
            filterable
            remote
            clearable
            :multiple-limit="1"
            reserve-keyword
            style="width: 100%"
            :placeholder="'项目名称'"
            :remote-method="remoteMethod"
            :loading="selectLoading"
            @change="selectChange"
          >
            <el-option
              v-for="(item, index) in poptions"
              :key="item.projectNo + index"
              :label="item.project_name"
              :value="item.projectNo + ''"
              :disabled="item.status !== '1'"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目竞价截止时间" class="clear" required label-width="140px">
          <el-input
            placeholder="项目竞价截止时间"
            v-model="ruleForm.pendtime"
            disabled
            maxlength="500"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8" v-if="ruleForm.is_project === '1'">
        <el-form-item label="要求到货时间" class="clear" required>
          <el-input
            placeholder="要求到货时间"
            v-model="ruleForm.arrtime"
            maxlength="500"
            disabled
          />
        </el-form-item>
      </el-col>

      <el-col :span="16" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目用途" class="clear" required>
          <el-input
            placeholder="项目用途"
            v-model="ruleForm.use_desc"
            disabled
            maxlength="500"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目总预算" class="clear" required>
          <el-input
            placeholder="项目总预算"
            v-model="ruleForm.budget_total"
            disabled
            maxlength="500"
          >
            <template slot="append">元</template></el-input
          >
        </el-form-item>
      </el-col>

      <el-col :span="24" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目商品要求" class="clear" required>
          <el-table
            ref="multipleTable"
            :data="ptableData"
            :size="'mini'"
            border
            stripe
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40"> </el-table-column>
            <el-table-column label="商品阶梯" width="70px">
              <template slot-scope="scope"> {{ scope.$index + 1 }}</template>
            </el-table-column>
            <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>
        </el-form-item>
      </el-col>
      <el-co :span="24">
        <el-form-item label="竞价商品要求" class="clear" required>
          <el-table :data="tableData" stripe border :size="'mini'" style="width: 100%">
            <el-table-column
              prop="arrival_time"
              label="到货时间"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="budget_price"
              label="预算单价"
              show-overflow-tooltip
              width="110"
            />
            <el-table-column prop="num" label="购买数量" show-overflow-tooltip width="80">
              <template slot-scope="scope">
                <span>{{ scope.row.num }}</span
                ><span>{{ scope.row.unit_name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="cat_id_name"
              label="商品分类"
              show-overflow-tooltip
              min-width="170"
            />

            <el-table-column
              prop="good_img"
              label="图片"
              width="50"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <img
                  v-viewer
                  style="width: 23px; height: 23px; margin: 0 5px 0 0"
                  class="fl"
                  v-if="scope.row.good_img"
                  :src="scope.row.good_img"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="good_name"
              label="商品名称"
              show-overflow-tooltip
              min-width="170"
            />
            <el-table-column
              prop="specinfo"
              label="商品规格"
              show-overflow-tooltip
              width="170"
            >
              <template slot-scope="scope">
                <span v-for="(si, sii) in scope.row.specinfo" :key="si.spec_name + sii"
                  ><span v-if="sii !== 0">-</span>{{ si.spec_name }}:[{{
                    si.spec_value_name
                  }}]</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="is_addrs"
              label="是否多地"
              width="70"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.is_addrs === "1" ? "多地" : "一地" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="is_custom"
              label="是否定制"
              width="70"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.is_custom === "1" ? "定制" : "非定制" }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" width="80">
              <template slot="header" slot-scope="scope">
                <span>操作</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  v-if="status === ''"
                  content="添加活动商品"
                  placement="top"
                >
                  <i
                    class="el-icon-circle-plus-outline fr"
                    style="font-size: 18px; margin-top: 2px"
                    @click="openEdit(-1, {})"
                  />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="修改" placement="top">
                  <i
                    class="el-icon-edit tb-icon"
                    @click="openEdit(scope.$index, scope.row)"
                  ></i>
                </el-tooltip>
                <el-tooltip
                  v-if="status === ''"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <i
                    class="el-icon-delete tb-icon"
                    @click="openCostEditDelete(scope.$index)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <add-edit-good-modal
          :showModel="showModel"
          :sitem="editItem"
          @cancel="showModel = false"
          @refresh="editGoodRefresh"
        />
      </el-co>
      <el-col :span="24" style="text-align: right" v-if="id === 'add'">
        <el-button type="primary" @click="submitForm" :size="'mini'">保 存</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/zixunOrder";
import resToken from "@/mixins/resToken";
import addEditGoodModal from "./addEditGoodModal";
import { mapGetters } from "vuex";
export default {
  name: "handover",
  props: ["id", "sitem", "newTime"],
  mixins: [resToken],
  components: {
    addEditGoodModal,
  },
  computed: {
    ...mapGetters(["business_companyNo"]),
  },
  data() {
    return {
      multipleSelection: [],
      // 表格 - 数据
      tableData: [],
      ptableData: [],
      showModel: false,
      editItem: {},
      options: [
        { value: "0", label: "非项目" },
        { value: "1", label: "项目" },
      ],
      statusOptions: [
        { value: "1", label: "竞品" },
        { value: "2", label: "竞聘" },
      ],
      configOptions: ["证书", "包装盒", "绒布袋", "标签", "其他"],
      poptions: [],
      loading: false,
      selectLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 60 * 60 * 24 * 1000;
        },
      },
      status: "", //存储详情接口返的状态
      ruleForm: {
        is_project: "0", //竞价类型 1非项目2项目，
        projectNo: [], //项目编号
        khNo: [], //客户编号
        customer_name: "", //客户名称
        companyNo: "",
        endtime: "", //竞价截止时间
        pendtime: "", //项目竞价截止时间
        platform_code: "", //平台id
        use_desc: "",
        budget_total: "",
        arrtime: "",
      },
      rulesThis: this.rules,
      // 验证规则
      rules: {
        companyNo: [
          {
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        khNo: [
          {
            type: "array",
            required: true,
            message: "请选择购买方公司",
            trigger: "change",
          },
        ],
        platform_code: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change",
          },
        ],
        endtime: [
          {
            required: true,
            message: "竞价截止时间不能为空",
            trigger: "change",
          },
        ],

        is_project: [
          {
            required: true,
            message: "请选择竞价类型！",
            trigger: "change",
          },
        ],
        projectNo: [
          {
            type: "array",
            required: true,
            message: "请选择项目",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "zixunOrderDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  mounted() {
    this.initForm();
  },
  watch: {
    id: function (val) {
      if (val) {
        this.initForm();
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.status = "";
      this.rulesThis = this.rules;
      this.disabled = false;
      await this.resetForm();
      this.loading = false;
    },
    openEdit(index, editItem) {
      const { is_project } = this.ruleForm;
      if (index + "" == "-1" && is_project === "1") {
        if (this.multipleSelection.length === 0) {
          this.$message.warning("请选择一个项目商品要求！");
          return;
        }
        if (this.multipleSelection.length > 1) {
          this.$message.warning("每次创建只能选择一个项目商品要求！");
          return;
        }
        const {
          cat_info,
          budget_price,
          pgNo,
          num,
          good_type,
          good_name,
          good_img,
        } = this.multipleSelection[0];
        let cat_id = [];
        if (cat_info && cat_info.length > 0) {
          cat_info.forEach((e) => {
            cat_id.push(e.id);
          });
        }
        console.log(this.multipleSelection[0]);
        this.editItem = {
          p_cat_info: cat_info,
          p_cat_id: cat_id,
          p_budget_price: budget_price,
          p_pgNo: pgNo,
          p_num: num,
          p_good_type: good_type,
          p_good_name: good_name,
          p_good_img: good_img,
          p_arrtime: this.ruleForm.arrtime,
        };
        this.editItem.index = index;
        this.showModel = true;
      } else {
        this.editItem = editItem;
        this.editItem.index = index;
        this.showModel = true;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    editGoodRefresh(e) {
      console.log(e);
      const { index } = e;
      if (index + "" === "-1") {
        this.tableData.push(JSON.parse(JSON.stringify(e)));
      } else {
        const fsindex = parseInt(index + "");
        this.tableData[fsindex] = JSON.parse(JSON.stringify(e));
        this.$set(this.tableData, fsindex, this.tableData[fsindex]);
      }
      this.showModel = false;
    },
    //竞价类型选择
    is_project_change() {
      const { is_project } = this.ruleForm;
      if (is_project === "0") {
      } else {
        this.ptableData = [];
      }
    },
    openCostEditDelete(index) {
      this.tableData.splice(index, 1);
    },
    async resetForm() {
      this.resign_name = "";
      this.hand_name = "";
      this.status = "";
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          let {
            is_project, //竞价类型 1销售2竞价，
            projectNo, //项目编号
            khNo, //客户编号
            customer_name, //客户名称
            companyNo,
            endtime, //竞价截止时间
            platform_code, //平台id
            ladder,
          } = this.sitem;

          this.ruleForm = {
            is_project: is_project || "0", //竞价类型 1项目 0 非项目
            projectNo: projectNo ? [projectNo] : [], //项目编号
            khNo: khNo ? [khNo] : [], //客户编号
            customer_name: customer_name || "", //客户名称
            companyNo: companyNo || this.business_companyNo || "",
            endtime: endtime || "", //竞价截止时间
            platform_code: platform_code || "", //平台id
            use_desc: "",
            budget_total: "",
            arrtime: "",
          };
          this.tableData =
            ladder && ladder.length > 0 ? JSON.parse(JSON.stringify(ladder)) : [];
          if (this.ruleForm.projectNo && this.ruleForm.projectNo.length === 1) {
            await this.selectChange(this.ruleForm.projectNo);
          }
        }
      });
    },
    async submitForm() {
      console.log(this.ruleForm);
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          if (this.tableData.length === 0) {
            this.$message.warning("至少提供一条商品要求！");
            this.loading = false;
            return;
          }
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          const { pendtime, is_project, endtime } = model;
          if (
            is_project === "1" &&
            new Date(endtime).getTime() > new Date(pendtime).getTime()
          ) {
            this.$message.warning("竞价截止时间不能晚于项目竞价截止时间！");
            this.loading = false;
            return;
          }
          if (new Date(endtime).getTime() <= new Date().getTime()) {
            this.$message.warning("竞价截止时间应该大于当前时间！");
            this.loading = false;
            return;
          }
          model.khNo = model.khNo.toString();
          model.projectNo = model.projectNo.toString();
          model.ladder = [];
          let list = JSON.parse(JSON.stringify(this.tableData));
          list.forEach((e) => {
            let im = {
              good_name: e.good_name,
              good_img: e.good_img,
              cat_id: e.cat_id[e.cat_id.length - 1],
              unit: e.unit.toString(),
              brand_id: e.brand_id.toString(),
              arrival_time: e.arrival_time,
              cost_desc: e.cost_desc,
              is_addrs: e.is_addrs,
              is_custom: e.is_custom,
              metal_id: e.metal_id,
              config: e.config.toString(),
              other_config: e.other_config,
              specs_weight: e.specs_weight,
              gold_price: e.gold_price,
              budget_price: e.budget_price,
              num: e.num,
              use_desc: e.use_desc,
              remark: e.remark,
              pgNo: e.pgNo,
              total_weight: e.total_weight,
              is_gold_price: e.is_gold_price,
              enclosure_file: e.enclosure_file,
              specinfo: [],
            };
            e.specinfo.forEach((a) => {
              let am = {
                specid: a.specid,
                spec_value_id: a.spec_value_id,
              };
              im.specinfo.push(am);
            });
            model.ladder.push(im);
          });

          console.log(model);
          const res = await asyncRequest.add(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "创建成功！",
              message: "",
            });
            this.$emit("refresh", true);
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // //获取规格值
    // setResData() {
    //   let list = JSON.parse(JSON.stringify(this.spec_tableData));
    //   let oldlist = JSON.parse(JSON.stringify(this.old_spec_tableData));
    //   let hasIDlist = [];
    //   list.forEach((a) => {
    //     if (a.id !== "") {
    //       hasIDlist.push(a);
    //     }
    //   });
    //   let newList = [];
    //   let resList = [];
    //   oldlist.forEach((a, ai) => {
    //     let item = null;
    //     let index = hasIDlist.findIndex((b) => a.id === b.id);
    //     if (index === -1) {
    //       item = JSON.parse(JSON.stringify(a));
    //       item.is_del = "1";
    //     } else {
    //       item = JSON.parse(JSON.stringify(hasIDlist[index]));
    //     }
    //     newList.push(item);
    //   });
    //   list.forEach((b) => {
    //     if (b.id === "") {
    //       b.is_del = "0";
    //       newList.push(b);
    //     }
    //   });
    //   newList.forEach((a) => {
    //     let m = {
    //       id: a.id,
    //       specid: a.specid,
    //       spec_value_id: a.spec_value_id,
    //       is_del: a.is_del || "0",
    //     };
    //     resList.push(m);
    //   });

    //   return resList;
    // },
    //项目选择
    async selectChange(e) {
      const key = e && e.length > 0 ? e[0] : "";
      if (key) {
        const { code, data, message } = await asyncRequest.pdetail({
          projectNo: key,
        });
        if (code === 0) {
          const { use_desc, budget_total, ladder, arrtime, endtime } = data;
          this.ruleForm.use_desc = use_desc || "";
          this.ruleForm.budget_total = budget_total || "";
          this.ruleForm.arrtime = arrtime || "";
          this.ruleForm.pendtime = endtime || "";
          this.ptableData = ladder;
          this.ptableData.forEach((e) => {
            e.cat_name = "";
            const { cat_info } = e;
            if (cat_info && cat_info.length > 0) {
              cat_info.forEach((b, bi) => {
                e.cat_name += bi !== 0 ? "/" + b.name : b.name;
              });
            }
          });
          this.tableData == [];
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
          this.ptableData = [];
          this.ruleForm.use_desc = "";
          this.ruleForm.budget_total = "";
          this.ruleForm.arrtime = "";
          this.tableData == [];
        }
      } else {
        this.ptableData = [];
        this.ruleForm.use_desc = "";
        this.ruleForm.budget_total = "";
        this.ruleForm.arrtime = "";
        this.tableData = [];
      }
    },
    async remoteMethod(query) {
      this.selectLoading = true;
      this.poptions = [];

      const { platform_code, companyNo, khNo } = JSON.parse(
        JSON.stringify(this.ruleForm)
      );
      if (!companyNo) {
        this.$message.warning("请选择销售方公司！");
        this.selectLoading = false;
        return;
      }
      if (khNo.length === 0) {
        this.$message.warning("请选择购买方公司！");
        this.selectLoading = false;
        return;
      }
      if (platform_code === "") {
        this.$message.warning("请选择所属平台！");
        this.selectLoading = false;
        return;
      }
      if (!query) {
        this.selectLoading = false;
        return;
      }

      let formValue = {
        page: 1,
        size: 100,
        khNo: khNo.toString(),
        companyNo: companyNo,
        platform_code: platform_code,
        status: "1",
        project_name: query,
      };

      const { code, data, message } = await asyncRequest.plist(formValue);
      if (code === 0) {
        const { list } = data;
        this.poptions = list;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
        this.poptions = [];
      }

      this.selectLoading = false;
    },
    //平台选择
    platform_code_codesearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.platform_code = id || "";
      this.$refs.ruleForm.validateField("platform_code");
      this.ruleForm.projectNo = [];
      this.ruleForm.budget_total = "0";
      this.ruleForm.use_desc = "";
      this.ruleForm.pendtime = "";
      this.ruleForm.arrtime = "";
      this.ptableData = [];
      this.tableData = [];
    },
    //销售方公司选择
    company_idsearchChange(e) {
      if (e) {
        const { id, code, label } = e;
        this.ruleForm.companyNo = code || "";
      }
      this.$refs.ruleForm.validateField("companyNo");
    },
    //购买方公司选择
    customerChange(e) {
      if (e && e.id) {
        this.ruleForm.khNo = [e.code];
        this.ruleForm.customer_name = e.label;
      } else {
        this.ruleForm.khNo = [];
        this.ruleForm.customer_name = "";
      }
      this.$refs.ruleForm.validateField("khNo");
      this.ruleForm.projectNo = [];
      this.ruleForm.budget_total = "0";
      this.ruleForm.use_desc = "";
      this.ruleForm.pendtime = "";
      this.ruleForm.arrtime = "";
      this.ptableData = [];
      this.tableData = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item-error-img {
  width: 100%;
  ul {
    width: 100%;
    li {
      float: left;
      border: 1px solid rgb(220, 223, 230);
      // border-left: 0;
      box-sizing: border-box;
      width: 254px;
      height: 164px;
      line-height: 164px;
      position: relative;
      img {
        display: inline-block;
        width: 100%;
        height: 100%;
      }
      .el-icon-close {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 2;
        width: 25px;
        height: 25px;
        text-align: center;
        line-height: 25px;
        font-size: 19px;
        &:hover {
          color: #6954f0;
        }
      }
    }
  }
}
.images_li {
  // width: 254px;
  // height: 164px;
  float: left;
}
.btnupload {
  float: left;
  border: 1px solid rgb(220, 223, 230);
  // border-left: 0;
  box-sizing: border-box;
  width: 254px;
  height: 164px;
  line-height: 164px;
  text-align: center;
}
.Upload {
  width: 254px;
  height: 164px;
  line-height: 164px;
  text-align: center;
  position: absolute;
  line-height: 0px;
  top: 0;
  left: 0;
  z-index: 2;
  line-height: 164px;
}
.avatar-uploader-icon {
  font-size: 33px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
</style>
