<template>
  <div>
    <div v-show="isCondition == 0">
      <el-header height="50px" class="header">
        <el-page-header
          @back="($parent.isShow = 1), ($parent.isFlag = '')"
          content="新增"
        >
        </el-page-header>
      </el-header>
      <div class="app-container">
        <div class="screen-container">
          <h4>销售政策信息</h4>
          <el-divider></el-divider>
          <el-form
            :model="searchForm"
            ref="form"
            label-width="120px"
            size="small"
            class="demo-searchForm"
          >
            <el-row>
              <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="销售政策编号">
                  <el-input
                    disabled
                    v-model="searchForm.code"
                    placeholder="如未填写，则系统自动生成"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="销售政策说明" prop="title">
                  <el-input
                    v-model="searchForm.title"
                    placeholder="销售政策说明"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="销售政策类型" prop="type">
                  <el-select
                    size="small"
                    v-model="searchForm.type"
                    placeholder="销售政策类型"
                    class="select_height"
                  >
                    <el-option
                      v-for="(item, index) in typeOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="产品品类" prop="mainId">
                  <el-select
                    v-model="searchForm.mainId"
                    :disabled="dataList.length ? true : false"
                    placeholder="请选择"
                    @change="handelStop"
                  >
                    <el-option
                      v-for="item in dictList"
                      :label="item.dictValue"
                      :value="item.dictCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="生效日期" prop="startTime">
                  <el-date-picker
                    v-model="searchForm.startTime"
                    type="datetime"
                    placeholder="生效日期"
                    default-time="00:00:00"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker> </el-form-item
              ></el-col>
              <el-col :xs="24" :ms="12" :lg="12">
                <el-form-item label="失效日期" prop="endTime">
                  <el-date-picker
                    v-model="searchForm.endTime"
                    type="datetime"
                    placeholder="失效日期"
                    default-time="00:00:00"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker> </el-form-item
              ></el-col>
              <el-col :xs="24" :ms="24" :lg="24">
                <el-form-item label="表头备注" prop="remark">
                  <el-input
                    v-model="searchForm.remark"
                    placeholder="新风机变频挂机。按提货数量1:3开单"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :ms="24" :lg="24">
                <el-form-item label="政策封面图">
                  <ImageUpload :fileList="fileList" :multiple="false" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="mymian-container">
          <el-row>
            <el-divider></el-divider>
            <el-row type="flex">
              <el-col :span="12">
                <h4 style="display: inline-block; margin-right: 20px">
                  货品信息
                </h4>
                <template>
                  <el-upload
                    class="import-btn"
                    :action="baseURL + 'student/import'"
                    :http-request="handleImport"
                    :file-list="importFileList"
                    :show-file-list="false"
                  >
                    <el-button type="primary" size="small"
                      >导入货品价格表</el-button
                    >
                  </el-upload>
                </template>

                <el-button
                  type="primary"
                  size="small"
                  @click="hanleDownloadFiles"
                  >下载模板</el-button
                >
              </el-col>
            </el-row>
            <el-divider></el-divider>
          </el-row>
          <el-table
            v-loading="listLoading"
            :data="dataList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="materialNumber"
              label="货品编码"
              align="center"
            >
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.materialNumber"
                  @change="handleK3List($event, scope.row)"
                  v-el-select-loadmore="loadmore"
                  filterable
                >
                  <el-option
                    v-for="item in k3List"
                    :key="item.id"
                    :label="item.number"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="materialName"
              label="货品名称"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="specification"
              label="规格型号"
              align="center"
            >
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.specification"
                  @change="handleK3List($event, scope.row)"
                  filterable
                >
                  <el-option
                    v-for="item in k3List"
                    :key="item.id"
                    :label="item.specification"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="saleTypeName"
              label="销售类型"
              align="center"
            >
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.saleTypeId"
                  @change="handleSalesType($event, scope.row)"
                  filterable
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.id"
                    :label="item.saleName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="saleTypeCode"
              label="销售类型编码"
              align="center"
            >
            </el-table-column>

            <el-table-column prop="discAmount" label="格力折扣" align="center">
              <template slot-scope="scope">
                <el-input
                  type="number"
                  v-model.number="scope.row.discAmount"
                  placeholder="请输入格力折扣"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" align="center">
              <template slot-scope="scope">
                <el-input
                  type="number"
                  v-model.number="scope.row.price"
                  placeholder="请输入单价"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="支付钱包" align="center">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  multiple
                  v-model="scope.row.walletIds"
                  filterable
                >
                  <el-option
                    v-for="item in NoRebateWalletList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <!-- <el-tag
                  style="margin: 5px"
                  type="success"
                  size="small"
                  v-for="item in scope.row.walletRelaList"
                  >{{ item.walletName }}</el-tag
                > -->
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="备注"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center">
              <template slot-scope="scope">
                <el-popconfirm
                  confirm-button-text="好的"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="内容确定删除吗？"
                  @onConfirm="hanleDelete(scope.row.id, scope.$index)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    class="textColor el-popover-left"
                    >删除</el-button
                  >
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div
            style="
              margin: 20px 20px 20px 0;
              display: flex;
              justify-content: space-between;
            "
          >
            <div>
              <el-button type="primary" size="small" @click="handleNewInfo"
                >添加</el-button
              >
              <el-button type="primary" size="small" @click="handleSave"
                >保存</el-button
              >
            </div>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="listTotal"
            >
            </el-pagination>
          </div>

          <el-row>
            <el-divider></el-divider>
            <el-row type="flex">
              <el-col :span="12">
                <h4 style="display: inline-block; margin-right: 20px">
                  条件信息
                </h4>
                <el-button type="primary" size="small" @click="isCondition = 1"
                  >添加</el-button
                ></el-col
              >
            </el-row>
            <el-divider></el-divider>
          </el-row>
          <el-table
            v-loading="listLoading"
            :data="conditionList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
          >
            <el-table-column
              fixed
              type="index"
              label="序号"
              width="50"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="name" label="限定条件" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.name"
                  style="text-align: center"
                  placeholder="请输入名称"
                  :disabled="scope.row.fang"
                  @blur="handleConditionName(scope.row)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              width="150"
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="scope.row.fang = false"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleCondition(scope.row.id, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div>
          <el-row>
            <el-divider></el-divider>
            <el-row type="flex" align="middle">
              <el-col :span="2">
                <h4>经销商信息</h4>
              </el-col>
            </el-row>
            <el-divider></el-divider>
          </el-row>
          <Transfer @handleAddPolicy="handleAddPolicy" />
        </div>
      </div>
    </div>
    <AddCondition
      v-show="isCondition == 1"
      @handleSubmitCon="handleSubmitCon"
    />
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import Minxin from "@/mixin";
import {
  addPoliy,
  getK3List,
  savePolicy,
  getTypeList,
  getWalletList,
  updateCondition,
  getMaterialList,
  deleteCondition,
  getConditionList,
  deleteMaterialPolicy,
  getNoRebateWalletList,
} from "@/api/policy_list";
import { getDictList } from "@/api/common";
import { downloadFiles, handleImport } from "@/utils/util";
import Transfer from "./Transfer";
import AddCondition from "./AddCondition";
import ImageUpload from "@/components/Common/image-upload.vue";
import { type } from "os";

export default {
  mixins: [Minxin],
    directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒⼦
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          /**
           * scrollHeight 获取元素内容⾼度(只读)
           * scrollTop 获取或者设置元素的偏移值,常⽤于, 计算滚动条的位置, 当⼀个元素的容器没有产⽣垂直⽅向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见⾼度(只读)
           * 如果元素滚动到底, 下⾯等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
  data() {
    return {
      fang: false,
      input: "",
      baseURL: "",
      isCondition: 0,
      searchForm: {
        code: "",
        endTime: "",
        imgSrc: "",
        remark: "",
        startTime: "",
        title: "",
        mainId: "",
        mainName: "",
        type: "",
      },
      dataList: [],
      addList: [],
      listLoading: false,
      dialogVisible: false,
      importFileList: [],
      fileList: [],
      options: {},
      value: "",
      typeList: [],
      walletList: [],
      typeOptions: [
        {
          value: "PROVISION",
          label: "配提",
        },
        {
          value: "LIMIT",
          label: "限量",
        },
      ],
      conditionList: [],
      dictList: [],
      k3List: [],
      NoRebateWalletList: [],
      sleectBox:{currentPage:1}
    };
  },
  computed: {
    ...mapGetters({
      comCode: "code",
    }),
  },

  mounted() {
    this.searchForm.code = this.comCode;
  },
  updated() {
    this.searchForm.code = this.comCode;
  },
  created() {
    this.getCommonApi();

    // console.log(this.$store.code);

    if (this.$parent.isFlag) {
      // this.handletwoList()
    }
  },
  methods: {
    ...mapMutations("sales", ["initData"]),
    //下载excel模板
    hanleDownloadFiles() {
      downloadFiles("/policy/download");
    },
    handleCondition(id, index) {
      deleteCondition({ id }).then((res) => {
        this.conditionList.splice(index, 1);
        Object.assign(
          this.$children[9].$data,
          this.$children[9].$options.data()
        );
        this.$successMsg("删除成功");
      });
    },
    loadmore() {
      this.sleectBox.currentPage++;
      this.getK3List();
    },
    getK3List(){
    getK3List({
        pageNum: this.sleectBox.currentPage,
        pageSize: 10,
        keyword: "",
      }).then((res) => {
        this.k3List = [...this.k3List,...res.data.records];
      });
    },

    getCommonApi() {
     this.getK3List()
      // 非返利钱包
      getNoRebateWalletList({ walletName: "" }).then((res) => {
        this.NoRebateWalletList = res.data;
        console.log(this.NoRebateWalletList, "kkkk");
      });
      const params = {
        pageNum: 1,
        pageSize: -1,
        saleCode: "",
        saleName: "",
        status: "",
      };
      // 获取销售类型列表
      getTypeList(params).then((res) => {
        this.typeList = res.data.records;
      });
      // this.handletwoList()
      // const params = {
      //   pageNum: 1,
      //   pageSize: 10,
      //   saleCode: "",
      //   saleName: "",
      //   status: "",
      // };
      // const walletParams = {
      //   pageNum: 1,
      //   pageSize: 10,
      //   mainName: "",
      //   saleTypeCode: "",
      //   saleTypeName: "",
      //   status: "",
      // };
      // // 获取钱包列表
      // getWalletList(walletParams).then((res) => {
      //   this.walletList = res.data.records;
      // });
      // getDictList({ sysDictEnum: "PRODUCT_TYPE" }).then((res) => {
      //   this.dictList = res.data;
      // });
    },
    handleSalesType(e, row) {
      const item = this.typeList.filter((k) => {
        return k.id == e;
      })[0];

      this.$set(row, "saleTypeCode", item.saleCode);
      this.$set(row, "saleTypeName", item.saleName);
      // this.$set(row,'saleTypeId',item.id)
    },
    //修改条件名称
    handleConditionName(row) {
      console.log(row.name);
      updateCondition({ id: row.id, name: row.name }).then((res) => {
        this.$successMsg("修改成功");
        row.fang = true;
      });
    },
    //提交信息
    handleSubmitCon() {
      const params = {
        policyId: this.comCode,
      };
      // 获取条件政策
      getConditionList(params).then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].fang = true;
        }
        this.conditionList = res.data;
      });
    },
    // 视图部分已注释，废弃的功能 fucn
    handelStop() {
      if (this.searchForm.mainId) {
        this.fang = true;
      } else {
        this.$errorMsg("请选择产品品类");
      }
    },
    // 导入
    async handleImport(param) {
      this.importLoading = true;
      const file = param.file;
      console.log(file, 123);
      const formData = new FormData();
      formData.append("file", file);
      formData.append("policyId", this.searchForm.code);
      // formData.append("mainId", this.searchForm.mainId);
      let result = await handleImport("/policy/material/import", formData);
      this.importLoading = false;
      this.importFileList = [];
      if (result.code == 200) {
        this.$alert(result.message, "导入成功", {
          confirmButtonText: "确定",
        });
        this.dataList = [];
        this.listTotal = 0;
        this.sleectBox.currentPage=1
        this.handletwoList();
      } else {
        this.$alert(result.message, "导入失败", {
          confirmButtonText: "确定",
        });
      }
    },
    getList() {
      if (this.$parent.isFlag) {
        this.handletwoList();
      }
    },
    // 获取货品信息
    handletwoList() {
      // this.searchForm.type
      const paramss = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        policyId: this.comCode,
        saleTypeCode: "",
      };

      getMaterialList(paramss)
        .then((result) => {
          result.data.records.forEach((k) => {
            k.walletIds = [];
            if (!k.specification) {
               k.materialNumber = k.materialId;
             k.specification = k.materialId;

            }else{
                k.materialNumber = k.materialNumber;
            k.specification = k.specification;
            }

            k.materialId = k.materialId;
            k.walletRelaList.forEach((l) => {
              l.id = l.walletId;
              l.name = l.walletName;
              k.walletIds = [...k.walletIds, l.walletId];
            });
          });

          this.dataList = [...this.dataList, ...result.data.records];
          this.listTotal = result.data.total;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 提交审核
    handleAddPolicy(policyCustomers) {
      if (!this.searchForm.title) {
        this.$errorMsg("请输入说明");
        return;
      }
      if (!this.searchForm.type) {
        this.$errorMsg("请选择类型");
        return;
      }
      if (!this.searchForm.startTime) {
        this.$errorMsg("请选择生效日期");
        return;
      }

      if (policyCustomers.length) {
        var arr = [];
        policyCustomers.forEach((el) => {
          arr.push({
            customerId: el.id,
            customerName: el.name,
            customerNumber: el.number,
            lastOrderTime: "",
            limitTakeNum: 0,
            policyId: this.comCode,
            policyTitle: "",
            remark: "",
          });
        });
        // this.dictList.forEach((k) => {
        //   if (k.dictCode == this.searchForm.mainId) {
        //     this.searchForm.mainName = k.dictValue;
        //   }
        // });
        const params = {
          adminCompanyId: "",
          code: "",
          customerCount: 0,
          examineBy: "",
          examineRemark: "",
          examineStatus: "",
          id: "",
          policyCustomers: arr,
          remark: "",
          status: true,
          title: "",
          type: "",
          ...this.searchForm,
          endTime: this.searchForm.endTime || "2100-01-01 00:00:00",
          imgSrc: this.fileList.length ? this.fileList[0].url : "",
        };
        console.log(this.fileList);
        addPoliy(params).then((res) => {
          console.log(res);
          this.$successMsg("新增成功");
          this.$parent.getList();
          this.$parent.isShow = 1;
        });
        return;
      } else {
        this.$errorMsg("选择经销商 ");
      }
    },
    //删除
    hanleDelete(id, index) {
      if (id) {
        const params = { policyMaterialId: id };
        deleteMaterialPolicy(params).then((res) => {
          this.dataList.splice(index, 1);
        });
      }
      this.dataList.splice(index, 1);
      this.listTotal -= 1;
      this.$successMsg("删除成功");
    },
    handleNewInfo() {
      // 物料列表
      this.dataList.push({
        id: "",
        discAmount: "",
        materialId: "",
        materialName: "",
        materialNumber: "",
        policyId: this.comCode,
        price: "",
        remark: "",
        saleTypeCode: "",
        saleTypeId: "",
        saleTypeName: "",
        specification: "",
        walletIds: "",
        walletRelaList: [],
      });
       this.sleectBox.currentPage =1
      this.listTotal += 1;
      // this.dataList.push(this.addList[this.addList.length-1])
    },
    handleSave() {
      if (!this.dataList.length) {
          return
      }
      for (let i = 0; i < this.dataList.length; i++) {
           if (!this.dataList[i].materialId) {
          this.$errorMsg("请选择货品");
          return
        }
        if (!this.dataList[i].saleTypeId) {
          this.$errorMsg("请选择销售类型");
          return
        }
        if (!this.dataList[i].discAmount) {
          this.$errorMsg("请输入格力折扣");
          return
        }
        if (!this.dataList[i].price) {
          this.$errorMsg("请输入单价");
          return
        }
        if (!this.dataList[i].walletIds.length) {
          this.$errorMsg("请选择钱包");
          return
        }

      }

      savePolicy(this.dataList).then((res) => {
        this.dataList = [];
        this.sleectBox.currentPage =1
        this.$successMsg("保存成功");
        this.handletwoList();
      });
    },
    handleK3List(e, row) {
      const item = this.k3List.filter((k) => {
        return k.id == e;
      })[0];
      // this.$set(row,'materialNumber',item.number)
      this.$set(row, "materialName", item.name);
      this.$set(row, "specification", item.specification);
      this.$set(row, "materialId", item.id);
    },
  },
  components: {
    Transfer,
    AddCondition,
    ImageUpload,
  },
};
</script>

<style lang="scss" scoped>
h4 {
  margin: 0;
}
.pdt {
  padding-top: 20px;
}
.import-btn {
  margin-right: 10px;
  display: inline-block;
}
.radio {
  padding: 20px 0;
}
.el-divider--horizontal {
  margin: 20px 0;
}
.el-container .el-divider--horizontal {
  margin: 10px;
}

.el-select {
  width: 100%;
}

.footer {
  margin-bottom: 20px;
}
</style>
