<template>
  <el-row>
    <el-col :span="24">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :size="'mini'"
        :rules="rulesThis"
        label-width="112px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                placeholder="项目名称"
                :disabled="type === 'view'"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属平台" prop="platform">
              <search-terrace
                :value="ruleForm.platform"
                :disabled="type === 'view'"
                :size="'mini'"
                :isDetail="type === 'view'"
                :is_show="'0'"
                :names="platform_name"
                :placeholder="'所属平台'"
                @searchChange="platform_codesearchChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售方" prop="companyNo">
              <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">
              <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="budget_total">
              <digital-input
                :values="ruleForm.budget_total"
                :placeholder="'项目总预算'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :disabled="type === 'view'"
                :controls="false"
                :append="'元'"
                @reschange="budget_total_change"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求到货时间" prop="arrtime">
              <el-date-picker
                v-model="ruleForm.arrtime"
                type="date"
                style="width: 100%"
                :disabled="type === 'view'"
                @change="time_change($event, 1)"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                placeholder="要求到货时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞价截止时间" prop="endtime">
              <el-date-picker
                v-model="ruleForm.endtime"
                type="datetime"
                style="width: 100%"
                :disabled="type === 'view'"
                @change="time_change($event, 2)"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                placeholder="要求到货时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目用途" prop="use_desc">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="项目用途"
                :disabled="type === 'view'"
                v-model="ruleForm.use_desc"
                maxlength="250"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品要求" prop="ladder">
              <el-table
                :data="ruleForm.ladder"
                :size="'mini'"
                border
                stripe
                style="width: 100%"
              >
                <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-column
                  fixed="right"
                  width="110"
                  v-if="type === 'add'"
                >
                  <template slot="header" slot-scope="scope">
                    <span>操作</span>
                    <el-tooltip
                      effect="dark"
                      content="添加阶梯"
                      placement="top"
                    >
                      <i
                        class="el-icon-circle-plus-outline tb-icon fr"
                        @click="openCostEdit(-1, {})"
                      ></i>
                    </el-tooltip>
                  </template>
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" content="修改" placement="top">
                      <i
                        class="el-icon-edit tb-icon"
                        @click="openCostEdit(scope.$index, scope.row)"
                      ></i>
                    </el-tooltip>

                    <el-tooltip 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>
            <!-- 弹窗 新增/修改 -->
            <cost-form-add-edit
              :index="costmodelIndex"
              :show-model="costshowModel"
              :sitem="costsitem"
              @refresh="costrefreshEdit"
              @cancel="costshowModel = false"
            />
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <el-col :span="24" style="text-align: right" v-if="type === 'add'">
      <el-button type="primary" :size="'mini'" @click="submitForm"
        >保 存
      </el-button>
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/project";
import resToken from "@/mixins/resToken";
import costFormAddEdit from "./costFormAddEdit";
import { mapGetters } from "vuex";

export default {
  name: "Account",
  props: ["showModel", "sitem", "id", "type", "newTime"],
  mixins: [resToken],
  components: { costFormAddEdit },
  computed: {
    ...mapGetters(["business_companyNo"]),
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  data() {
    const validate_sale_price = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("项目总预算不能为空！"));
      } else if (
        value === "0" ||
        value === "0." ||
        value === "0.0" ||
        value === "0.00"
      ) {
        callback(new Error("项目总预算不能为零！"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      tableData: [],
      costshowModel: false,
      costmodelIndex: "",
      costsitem: {},
      statusOptions: [
        { value: "1", label: "竞品" },
        { value: "2", label: "竞聘" },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
        },
      },

      company: "",
      platform_name: "",
      ruleForm: {
        name: "",
        platform: "",
        companyNo: "",
        khNo: [],
        customer_name: "",
        budget_total: "0",
        arrtime: "",
        endtime: "",
        use_desc: "",
        ladder: [],
      },
      rulesThis: this.rules,
      rules: {
        name: [
          {
            required: true,
            message: "项目名称不能为空！",
            trigger: "blur",
          },
        ],
        platform: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change",
          },
        ],
        companyNo: [
          {
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        khNo: [
          {
            type: "array",
            required: true,
            message: "请选择购买方公司",
            trigger: "change",
          },
        ],

        budget_total: [
          {
            required: true,
            validator: validate_sale_price,
            trigger: "blur",
          },
        ],

        arrtime: [
          {
            required: true,
            message: "要求到货时间不能为空！",
            trigger: "change",
          },
        ],

        endtime: [
          {
            required: true,
            message: "竞价截止时间不能为空！",
            trigger: "change",
          },
        ],
        use_desc: [
          {
            required: true,
            message: "项目用途不能为空",
            trigger: "blur",
          },
        ],
        ladder: [
          {
            type: "array",
            required: true,
            message: "至少添加两个商品要求",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    //商品要求阶梯修改
    costrefreshEdit(e) {
      let item = JSON.parse(JSON.stringify(e));
      const {
        index,
        id,
        budget_price,
        num,
        cat_name,
        good_img,
        good_name,
        good_type,
        cat_id,
      } = item;
      if (index + "" === "-1") {
        this.ruleForm.ladder.push(item);
      } else {
        console.log(item);
        this.ruleForm.ladder.forEach((i, findex) => {
          if (findex === parseInt(index)) {
            this.ruleForm.ladder[findex].id = id;
            this.ruleForm.ladder[findex].budget_price = budget_price;
            this.ruleForm.ladder[findex].num = num;
            this.ruleForm.ladder[findex].good_type = good_type;
            this.ruleForm.ladder[findex].cat_id = JSON.parse(
              JSON.stringify(cat_id)
            );
            this.ruleForm.ladder[findex].cat_name = JSON.parse(
              JSON.stringify(cat_name)
            );
            this.ruleForm.ladder[findex].good_name = good_name;
            this.ruleForm.ladder[findex].good_img = good_img;
          }
        });
      }
      this.showModel = false;
      this.$refs.ruleForm.validateField("ladder");
    },
    time_change(e, type) {
      const { arrtime, endtime } = this.ruleForm;
      if (
        arrtime &&
        endtime &&
        new Date(endtime).getTime() >= new Date(arrtime).getTime()
      ) {
        this.$message.warning("竞价截止时间不能大于要求到货时间！");
        if (type === 1) {
          this.ruleForm.arrtime = "";
        } else if (type === 2) {
          this.ruleForm.endtime = "";
        }
      }
      this.$refs.ruleForm.validateField("arrtime");
      this.$refs.ruleForm.validateField("endtime");
    },
    //平台选择
    platform_codesearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.platform = id || "";
      this.$refs.ruleForm.validateField("platform");
    },
    //销售方公司选择
    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");
    },
    //项目总预算编辑
    budget_total_change(e) {
      this.ruleForm.budget_total = e + "";
      this.$refs.ruleForm.validateField("budget_total");
    },
    //商品要求阶梯弹窗打开
    openCostEdit(index, sitem) {
      this.costmodelIndex = index;
      this.costsitem = sitem;
      this.costshowModel = true;
    },
    //删除某一商品要求
    openCostEditDelete(index) {
      this.ruleForm.ladder.splice(index, 1);
      this.$refs.ruleForm.validateField("ladder");
    },
    //初始化整个组件
    async initForm() {
      this.loading = true;
      this.company = "";
      this.ruleForm = {
        name: "",
        platform: "",
        companyNo: this.business_companyNo || "",
        khNo: [],
        customer_name: "",
        budget_total: "0",
        arrtime: "",
        endtime: "",
        use_desc: "",
        ladder: [],
      };
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    //初始化整个表单
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          console.log(this.sitem);
          const {
            project_name,
            budget_total,
            ladder,
            use_desc,
            arrtime,
            endtime,
            khName,
            company,
            khNo,
            companyNo,
            platform_id,
            platform_name,
          } = this.sitem;
          this.company = company || "";
          this.platform_name = platform_name || "";
          this.ruleForm = {
            name: project_name || "",
            platform: platform_id || "",
            companyNo: companyNo || "",
            khNo: khNo ? [khNo] : [],
            customer_name: khName || "",
            budget_total: budget_total || "0",
            arrtime: arrtime || "",
            endtime: endtime || "",
            use_desc: use_desc || "",
            ladder: ladder && ladder.length > 0 ? ladder : [],
          };
          this.ruleForm.ladder.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;
              });
            }
          });
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          console.log(model);
          const { budget_total, ladder } = model;
          let ztotal = Math.floor(budget_total * 100) / 100;
          // model.platform = model.platform.toString();
          model.khNo = model.khNo.toString();
          delete model["customer_name"];
          if (ladder && ladder.length < 2) {
            this.$message.warning("至少添加两个商品要求!");
            this.loading = false;
            return;
          }
          let total = 0;
          let list = [];
          ladder.forEach((e) => {
            let item = JSON.parse(JSON.stringify(e));
            delete item["id"];
            delete item["index"];
            delete item["is_del"];
            delete item["cat_name"];
            item.cat_id =
              item.cat_id && item.cat_id.length > 0
                ? item.cat_id[item.cat_id.length - 1]
                : "";
            list.push(item);
            let a1 = Math.floor(e.budget_price * 100);
            let a2 = parseInt(e.num);
            let a3 = (a1 * a2) / 100;
            total = Math.floor((a3 + total) * 100) / 100;
          });
          console.log(`项目总预算为${ztotal}---商品要求预算总和为${total}`);
          if (ztotal < total) {
            this.$message.warning("项目总预算不能低于所以商品要求预算总和!");
            this.loading = false;
            return;
          }
          model.ladder = JSON.parse(JSON.stringify(list));

          let res = await asyncRequest.add(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "添加成功",
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh", res.data);
          } 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;
        }
      });
    },
  },
};
</script>

   <style lang="scss" scoped>
.account {
}
</style>
