<template>
  <div>
    <div>
    <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"
          :rules="rules"
          ref="searchForm"
          label-width="120px"
          size="small"
          class="demo-searchForm"
        >
          <el-row>
            <el-col :xs="24" :ms="12" :lg="12">
              <el-form-item label="销售政策编号" prop="code">
                <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="name">
                <el-select v-model="value" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in walletList"
                    :key="index"
                    :label="item.mainName"
                    :value="item.mainId"
                  >
                  </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="政策封面图" prop="imgSrc">
                <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>
              <el-upload
                class="import-btn"
                :action="baseURL + 'student/import'"
                :http-request="handleImport"
                :file-list="importFileList"
                :show-file-list="false"
              >
                <el-button size="small">导入货品价格表</el-button>
              </el-upload>
              <el-button 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
            fixed
            prop="num"
            label="序号"
            width="50"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="materialNumber"
            label="货品编码"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="materialName" label="货品名称" align="center">
          </el-table-column>
          <el-table-column prop="specification" label="规格型号" align="center">
          </el-table-column>
          <el-table-column
            prop="saleTypeCode"
            label="销售类型编码"
            width="500"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleTypeName" label="销售类型" align="center">
          </el-table-column>
          <el-table-column prop="price" label="单价" align="center">
          </el-table-column>
          <el-table-column label="支付钱包" align="center">
            <template slot-scope="scope">
                <el-tag style="margin:10px" type="success" size="small" v-for=" item  in  scope.row.walletRelaList">{{item.walletName}}</el-tag>
            </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)"
              >
                <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">
          <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 size="small" @click="$parent.isShow = 3"
                >添加</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">
              限定条件{{scope.$index+1}}
            </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="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  />
  </div>
</template>

<script>
import { mapState,mapMutations } from "vuex";
import Minxin from "@/mixin";
import {
  addPoliy,
  getTypeList,
  getWalletList,
  getMaterialList,
  deleteCondition,
  getConditionList,
  deleteMaterialPolicy,
} from "@/api/supply/sales";
import { downloadFiles, handleImport } from "@/utils/util";
import Transfer from "./Transfer";
import Pagination from "@/components/Pagination";
import ImageUpload from "@/components/Common/image-upload.vue";

export default {
  mixins: [Minxin],
  data() {
    return {
      input: "",
      baseURL: "",
      searchForm: {
        code: "",
        endTime: "",
        imgSrc: "",
        remark: "",
        startTime: "",
        title: "",
        type: "",
      },
      listLoading: false,
      rules: {
        name: [
          { required: true, message: "", trigger: "click" },
          { min: 3, max: 5, message: "", trigger: "click" },
        ],
      },
      importFileList: [],
      fileList: [],
      options: {},
      value: "",
      typeList: [],
      walletList: [],
      typeOptions: [
        {
          value: "PROVISION",
          label: "配提",
        },
        {
          value: "LIMIT",
          label: "限量",
        },
      ],
      conditionList: [],
    };
  },
  computed: mapState({
    comCode: (state) => {
      return state.sales.code;
    },
    newForm:(state) => {
      return state.sales.searchForm;
    },
    imgFile:(state) => {
      return state.sales.fileList;
    },
  }),
  created() {
    this.getCommonApi();
    if (this.$parent.isFlag) {
      const params = {
        policyId: this.comCode,
      };
      // 获取条件政策
      getConditionList(params).then((res) => {
        this.conditionList = res.data;

      });
      // this.handletwoList()
    }
  },
  updated() {
    this.searchForm = this.newForm
    this.searchForm.code = this.comCode;
    this.fileList = this.imgFile
  },
  methods: {
    ...mapMutations('sales',['initData']),
    //下载excel模板
    hanleDownloadFiles() {
      downloadFiles("/policy/download");
    },
    handleCondition(id,index){
      deleteCondition({id}).then(res=>{
            this.conditionList.splice(index,1)
        this.$successMsg('删除成功')
      })
    },
    getCommonApi() {
      // this.handletwoList()
      const params = {
        pageNum: 1,
        pageSize: 10,
        saleCode: "",
        saleName: "",
        status: "",
      };
      const walletParams = {
        pageNum: 1,
        pageSize: 10,
        mainName: "",
        saleTypeCode: "",
        saleTypeName: "",
        status: "",
      };
      // 获取销售类型列表
      getTypeList(params).then((res) => {
        this.typeList = res.data.records;
        console.log(this.typeList, "type");
      });
      // 获取钱包列表
      getWalletList(walletParams).then((res) => {
        this.walletList = res.data.records;
      });
    },
    // 导入
    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);
      let result = await handleImport("/policy/material/import", formData);
      this.importLoading = false;
      this.importFileList = [];
      if (result.code == 200) {
        this.$alert(result.message, "导入成功", {
          confirmButtonText: "确定",
        });

        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: "",
      };
      console.log(45454);
      getMaterialList(paramss)
        .then((result) => {
          this.dataList = result.data.records;

          this.listTotal = result.data.total;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 提交审核
    handleAddPolicy(policyCustomers) {
      //     console.log(this.fileList,'上传图片');
      // return
      console.log(policyCustomers, "选择的经销商");
      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: "",
          });
        });
        const params = {
          adminCompanyId: "",
          code: "",
          customerCount: 0,

          examineBy: "",
          examineRemark: "",
          examineStatus: "",

          id: "",
          imgSrc: this.fileList.length?this.fileList[0].url:'',
          policyCustomers: arr,
          remark: "",
          status: true,
          title: "",
          type: "",
          ...this.searchForm,
        };
        addPoliy(params).then((res) => {
          console.log(res);
          this.$successMsg("新增成功");
          this.fileList = [];
          this.$parent.getList()
          this.$parent.isShow = 1;
        });
        return;
      }
      this.$errorMsg("选择经销商 ");
    },
    //删除
    hanleDelete(id) {
      const params = { policyMaterialId: id };
      deleteMaterialPolicy(params).then((res) => {
        this.$successMsg("删除成功");
        this.handletwoList();
      });
    },
  },
  components: {
    Transfer,
    Pagination,
    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>
