<template>
  <el-form
    ref="ruleForm"
    :loading="loading"
    :model="ruleForm"
    status-icon
    :size="'mini'"
    :rules="rulesThis"
    label-width="86px"
    style="width: 100%"
  >
    <el-row>
      <el-col :span="6">
        <el-form-item label="竞价类型" prop="is_project" class="clear">
          <el-select
            v-model="ruleForm.is_project"
            style="width: 100%"
            :disabled="false"
            placeholder="竞价类型"
            @change="projectChange([])"
          >
            <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="6">
        <el-form-item
          label="竞价截止时间"
          label-width="110px"
          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="12">
        <el-form-item label="所属平台" prop="platform_code" class="clear">
          <search-terrace
            :value="ruleForm.platform_code"
            :disabled="type === 'view' || ruleForm.is_project === '1'"
            :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="12">
        <el-form-item label="销售方" prop="companyNo" class="clear">
          <el-input :value="getCompanyWithCode(ruleForm.companyNo).name" disabled />
        </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' || ruleForm.is_project === '1'"
            :is-detail="type === 'view' || ruleForm.is_project === '1'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="ruleForm.is_project === '1'">
        <el-form-item label="项目信息" prop="projectNo" class="clear">
          <show-data-table
            :newTime="fnewTime"
            v-if="fnewTime !== '' && ruleForm.projectNo !== ''"
            :sitem="projectSitem"
            border
            :columns="projectColumns"
          />
          <div class="hasHover" v-else @click="showProjectModel = true">
            <el-alert
              center
              show-icon
              title="点击此处选择项目"
              type="warning"
              :closable="false"
            />
          </div>
        </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-col :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"
          :company-no="currentCompany"
          @cancel="showModel = false"
          @refresh="editGoodRefresh"
        />
        <search-project-modal
          :once="true"
          :showModel="showProjectModel"
          @cancel="showProjectModel = false"
          :status="'1'"
          @searchChange="projectChange"
        />
      </el-col>
      <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";
import { projectColumns } from "./ShowDataTableColumns";
import searchProjectModal from "@/components/search-project-modal/index.vue";
import companyHelper from '@/mixins/companyHelper'


export default {
  name: "handover",
  props: ["id", "sitem", "newTime"],
  mixins: [resToken, companyHelper],
  components: {
    addEditGoodModal,
    searchProjectModal,
  },
  computed: {
    ...mapGetters(["business_companyNo"]),
      powers() {
      const { btnList } = this.$store.getters
      const tran = btnList.find( (item) => item.menu_route == "zixunOrderDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      showProjectModel: false,
      multipleSelection: [],
      fnewTime: "",
      pay_name: "",
      // 表格 - 数据
      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,
      projectColumns,
      projectSitem: null,
      // 验证规则
      rules: {
        companyNo: [
          {
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        khNo: [
          {
            type: "array",
            required: true,
            message: "请选择购买方公司",
            trigger: "change",
          },
        ],
        platform_code: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change",
          },
        ],
        pay_id: [
          {
            required: true,
            message: "请选择支付渠道",
            trigger: "change",
          },
        ],
        endtime: [
          {
            required: true,
            message: "竞价截止时间不能为空",
            trigger: "change",
          },
        ],

        is_project: [
          {
            required: true,
            message: "请选择竞价类型！",
            trigger: "change",
          },
        ],
        projectNo: [
          {
            required: true,
            message: "请选择项目",
            trigger: "change",
          },
        ],
      },
    };
  },
  async mounted() {
    await this.initForm();
    await this.onCompanyChange()
    
  },
  watch: {
    id: function (val) {
      if (val) {
        this.initForm();
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  methods: {
    onCompanyChange(){
      this.ruleForm.companyNo = this.currentCompany
    },
    async initForm() {
      this.loading = true;
      this.status = "";
      this.rulesThis = this.rules;
      this.disabled = false;
      await this.resetForm();
      this.getNewTime();
      this.loading = false;
    },
    openEdit(index, editItem) {
      const { is_project } = this.ruleForm;
      if(!this.currentIsBusinessCompany()) return

      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);
          });
        }

        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.projectSitem.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;
    },
    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,
            pay_id,
            pay_name,
          } = this.sitem;

          this.ruleForm = {
            is_project: is_project || "0", //竞价类型 1项目 0 非项目
            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: "",
            pay_id: pay_id || "",
          };
          this.tableData =
            ladder && ladder.length > 0 ? JSON.parse(JSON.stringify(ladder)) : [];
          this.pay_name =
            pay_id + "" == "0" ? "不选择" : pay_id + "" === "" ? "" : pay_name;
          if (this.ruleForm.projectNo) {
            await this.projectChange([{ projectNo: this.ruleForm.projectNo }]);
          }
        }
      });
    },
    async submitForm() {
      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 { is_project, endtime } = model;
          const pendtime = this.projectSitem ? this.projectSitem.endtime : "";
          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 = [];
          model.companyNo = this.currentCompany
          
          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 { code, data, message } = await asyncRequest.add(model);
          this.loading = false;
          if (code === 0) {
            this.$notify.success({
              title: "创建成功！",
              message: "",
            });
            this.$emit("refresh", true);
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //项目选择
    async projectChange(e) {
      const { is_project } = this.ruleForm;
      if (is_project + "" === "1") {
        const key = e && e.length > 0 ? e[0].projectNo : "";
        if (key) {
          const { code, data, message } = await asyncRequest.pdetail({
            projectNo: key,
          });
          if (code === 0) {
            const {
              khNo,
              khName,
              pay_id,
              pay_name,
              platform_id,
              platform_name,
              ladder,
              companyNo,
              company,
            } = data;
            this.ruleForm.projectNo = key;
            this.projectSitem = JSON.parse(JSON.stringify(data));

            //平台赋值
            this.platform_code_codesearchChange({
              id: platform_id,
              code: platform_id,
              label: platform_name,
            });
            //支付渠道赋值
            this.pay_id_change({
              id: pay_id,
              code: pay_id,
              label: pay_id + "" == "0" ? "不选择" : pay_name,
            });
            //销售方公司赋值
            this.company_idsearchChange({
              id: companyNo,
              code: companyNo,
              label: company,
            });
            //购买方公司赋值
            this.customerChange({
              id: khNo,
              code: khNo,
              label: khName,
            });
            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();
            this.resetProject();
          } else {
            this.$message.warning(message);
            this.resetProject();
          }
        } else {
          //平台赋值
          this.platform_code_codesearchChange({
            id: "",
            code: "",
            label: "",
          });
          //支付渠道赋值
          this.pay_id_change({
            id: "",
            code: "",
            label: "",
          });
          //销售方公司赋值
          this.company_idsearchChange({
            id: "",
            code: "",
            label: "",
          });
          //购买方公司赋值
          this.customerChange({
            id: "",
            code: "",
            label: "",
          });
          this.resetProject();
        }
      } else {
        this.resetProject();
      }

      this.getNewTime();
    },
    resetProject() {
      this.ruleForm.projectNo = "";
      this.projectSitem = null;
      this.ptableData = [];
      this.tableData = [];
    },

    //平台选择
    platform_code_codesearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.platform_code = id || "";
      this.$refs.ruleForm.validateField("platform_code");
    },

    //支付渠道选择
    pay_id_change(e) {
      const { id, code, label } = e;
      this.ruleForm.pay_id = id || "";
      this.pay_name = label || "";
      this.$refs.ruleForm.validateField("pay_id");
    },
    //销售方公司选择
    company_idsearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.companyNo = code || "";
      this.$refs.ruleForm.validateField("companyNo");
    },
    //购买方公司选择
    customerChange(e) {
      const { id, code, label } = e;
      this.ruleForm.khNo = code ? [code] : [];
      this.ruleForm.customer_name = label ? label : "";
      this.$refs.ruleForm.validateField("khNo");
    },
    getNewTime() {
      this.fnewTime = new Date().valueOf();
    },
  },
};
</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>
