<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入店铺电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="isAudit">
        <el-select v-model="queryParams.isAudit" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in isAuditOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登录帐号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入登录帐号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="店铺id" align="center" prop="storeId" width="120px"/>
      <el-table-column label="店铺名称" align="center" prop="storeName" width="120px"/>
      <el-table-column label="机构全称" align="center" prop="fullName" width="120px"/>
      <el-table-column label="店铺LOGO" align="center" prop="logoUrl" width="100px">
          <template slot-scope="scope">
             <el-popover
               placement="right"
               title=""
               trigger="hover">
               <img slot="reference" :src="scope.row.logoUrl" width="80px">
               <img :src="scope.row.logoUrl" style="max-width: 150px;">
             </el-popover>
          </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" width="200px"/>
      <el-table-column label="店铺电话" align="center" prop="phone" width="120px"/>
      <el-table-column label="资质证书" align="center" prop="licenseImages" width="100px">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover">
            <img slot="reference" :src="scope.row.licenseImages" width="80px">
            <img :src="scope.row.licenseImages" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="isAudit">
        <template slot-scope="scope">
          <dict-tag :options="isAuditOptions" :value="scope.row.isAudit"/>
        </template>
      </el-table-column>
      <el-table-column label="商品总数" align="center" prop="productCount" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="salesCount" />
      <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="累计金额" align="center" prop="totalMoney" />
      <el-table-column label="登录帐号" align="center" prop="account" width="150px" />
      <el-table-column label="创建时间" align="center" prop="createTime"  width="150px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:store:edit']"
          >修改</el-button>
           <el-button
             size="mini"
               type="text"
               @click="handledetails(scope.row)"
             >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:store:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改店铺管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
              <el-form-item label="店铺名称" prop="storeName">
                <el-input v-model="form.storeName" placeholder="请输入店铺名称" />
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="店铺电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入店铺电话" />
              </el-form-item>
          </el-col>
        </el-row>
              <el-form-item label="机构全称" prop="fullName">
                <el-input v-model="form.fullName" placeholder="请输入机构全称" />
              </el-form-item>
        <el-row>
            <el-col :span="12">
              <el-form-item label="店铺LOGO" prop="logoUrl">
               <el-upload
                 v-model="form.logoUrl"
                 class="avatar-uploader"
                 :action="uploadUrl"
                 :show-file-list="false"
                 :on-success="handleAvatarSuccess"
                 :before-upload="beforeAvatarUpload">
                 <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" width="200px">
                 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
        	</el-col>
        </el-row>
        <el-form-item label="资质证书" prop="licenseImages">
          <el-upload
            v-model="form.licenseImages"
            class="avatar-uploader"
            :action="licenseuploadUrl"
            :show-file-list="false"
            :on-success="licensehandleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.licenseImages" :src="form.licenseImages" class="avatar" width="200px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>          
          </el-upload>
        </el-form-item>
        <el-form-item label="店铺介绍" prop="descs" >
          <el-input v-model="form.descs" placeholder="请输入店铺介绍" type="textarea"/>
        </el-form-item>
         <el-row>
          <el-col :span="12">
            <el-form-item label="所属城市" prop="cityIds">
            <el-cascader
              ref="citySelect"
              v-model="form.cityIds"
              :options="citys"
              @change="handleCityChange">
              </el-cascader>        
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入地址" />
              </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="退货地址" prop="refundAddress">
          <el-input v-model="form.refundAddress" placeholder="请输入退货地址" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
          <el-form-item label="退货电话" prop="refundPhone">
            <el-input v-model="form.refundPhone" placeholder="请输入退货电话" />
          </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="退货收货人" prop="refundConsignee">
              <el-input v-model="form.refundConsignee" placeholder="请输入退货收货人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="寄件人电话" prop="sendPhone">
          <el-input v-model="form.sendPhone" placeholder="请输入寄件人电话" />
        </el-form-item>
          <el-row>
          <el-col :span="12">
            <el-form-item label="商品总数" prop="productCount">
               <el-input-number v-model="form.productCount"  :min="0" label="描述文字"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="salesCount">
               <el-input-number v-model="form.salesCount"  :min="0" label="描述文字"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="累计金额" prop="totalMoney">
                 <el-input-number v-model="form.totalMoney" :precision="2" :step="0.1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
             <!-- <el-form-item label="分佣比例%" prop="shippingType">
                    <el-input-number v-model="form.brokerageRate" :min="0" :max="100"></el-input-number>
               </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="parseInt(dict.dictValue)"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分佣方式" prop="brokerageType" >
                 <el-radio v-model="form.brokerageType" label="1">每盒</el-radio>
                 <el-radio v-model="form.brokerageType" label="2">总价</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="配送方式" prop="shippingType">
                <el-checkbox-group v-model="form.shippingType" size="medium">
                 <el-checkbox v-for="(item, index) in shippingTypeOptions" :key="index" :label="item.value"
                            :disabled="item.disabled">{{item.label}}</el-checkbox>
                 </el-checkbox-group>
           </el-form-item>

           <el-form-item label="发货方式" prop="deliveryType">
                 <el-radio-group v-model="form.deliveryType">
                          <el-radio :label="item.dictValue" v-for="item in deliveryTypeOptions" >{{item.dictLabel}}</el-radio>
                 </el-radio-group>
            </el-form-item>

          <el-form-item label="登录帐号" prop="account" v-if="title != '修改店铺管理'">
            <el-input v-model="form.account" placeholder="请输入登录帐号" />
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
      <el-drawer
            :with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <storeDetails  ref="Details" />
       </el-drawer>


  </div>
</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore, exportStore } from "@/api/his/store";
import storeDetails from '../../components/his/storeDetails.vue';
import {getCitys} from "@/api/store/city";
export default {
  name: "Store",
  components: { storeDetails },
  data() {
    return {
      show:{
              title:"店铺详情",
              open:false,
            },
shippingType:[],
      citys:[],
      licenseuploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
            uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
            baseUrl: process.env.VUE_APP_BASE_API,
      shippingTypeOptions: [{
        "label": "配送",
        "value": "1"
      }, {
        "label": "自提",
        "value": "2"
      }, {
        "label": "配送自提",
        "value": "3"
      }],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺管理表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 审核状态字典
      isAuditOptions: [],
      deliveryTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        address: null,
        phone: null,
        status: null,
        isAudit: null,
        account: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeName: [
         { required: true, message: "店铺名称不能为空", trigger: "blur" }
       ],
       logoUrl: [
         { required: true, message: "店铺LOGO不能为空", trigger: "blur" }
       ],
       cityIds: [
         { required: true, message: "所属城市不能为空", trigger: "blur" }
       ],
      address: [
        { required: true, message: "地址不能为空", trigger: "blur" }
      ],
      licenseImages: [
        { required: true, message: "资质证书不能为空", trigger: "blur" }
      ],
      shippingType: [
        { required: true, message: "配送方式不能为空", trigger: "blur" }
      ],
      account: [
        { required: true, message: "登录账号不能为空", trigger: "blur" }
      ],
      brokerageType: [
        { required: true, message: "分佣方式不能为空", trigger: "blur" }
      ],
      refundPhone: [
        { required: true, message: "退货电话不能为空", trigger: "blur" }
      ],
      refundAddress: [
        { required: true, message: "退货地址不能为空", trigger: "blur" }
      ],
      refundConsignee: [
        { required: true, message: "退货收货人不能为空", trigger: "blur" }
      ],
      deliveryType: [
        { required: true, message: "发货方式不能为空", trigger: "blur" }
      ],
      sendPhone: [
        { required: true, message: "寄件人电话不能为空", trigger: "blur" },
      ],
      phone:  [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],

      password: [
        { required: true, message: "新密码不能为空", trigger: "blur" },
        { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
      ],
      }
    };
  },
  created() {
      this.getCitys();
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_company_isaudit").then(response => {
      this.isAuditOptions = response.data;
    });
    this.getDicts("sys_store_delivery_type").then(response => {
      this.deliveryTypeOptions = response.data;
    });
  },
  methods: {

    handledetails(row){
            this.show.open=true;
            setTimeout(() => {
                 this.$refs.Details.getDetails(row.storeId);
            }, 1);
        },

    handleCityChange(value) {
          var nodes=this.$refs.citySelect.getCheckedNodes();
          this.form.address=nodes[0].pathLabels[0]+nodes[0].pathLabels[1]+nodes[0].pathLabels[2];
          this.form.cityIds=value.toString();
        },
        getCitys(){
            getCitys().then(res => {
              this.loading = false;
              this.citys=res.data;
            })
        },

    licensehandleAvatarSuccess(res, file) {
        if(res.code==200){
          this.form.licenseImages=res.url;
          this.$forceUpdate()
        }
        else{
          this.msgError(res.msg);
        }
    },
        handleAvatarSuccess(res, file) {
            if(res.code==200){
              this.form.logoUrl=res.url;
              this.$forceUpdate()
            }
            else{
              this.msgError(res.msg);
            }
        },
        beforeAvatarUpload(file) {
          const isLt1M = file.size / 1024 / 1024 < 1;
          if (!isLt1M) {
            this.$message.error('上传图片大小不能超过 1MB!');
          }
          return   isLt1M;
        },


    /** 查询店铺管理列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        cityIds: null,
        storeName: null,
        descs: null,
        logoUrl: null,
        address: null,
        lng: null,
        lat: null,
        phone: null,
        licenseImages: null,
        productCount: null,
        status: 0,
        createTime: null,
        updateTime: null,
        salesCount: null,
        balance: null,
        totalMoney: null,
        isAudit: 0,
        account: null,
        password: null,
        shippingType: ["1"],
        brokerageType:"1",
        brokerageRate:0,
        fullName:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.storeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺管理";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storeId = row.storeId || this.ids
      getStore(storeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺管理";
        var str=this.form.shippingType
        this.form.shippingType=str.split(",")
        this.form.cityIds=((this.form.cityIds).split(",")).map(Number)
        if(this.form.brokerageType!=null ){
          this.form.brokerageType=JSON.stringify(this.form.brokerageType)
        }
        if(this.form.deliveryType!=null ){
          this.form.deliveryType=JSON.stringify(this.form.deliveryType)
        }



      });
    },
    /** 提交按钮 */
    submitForm() {


      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cityIds=(this.form.cityIds).toString()
          this.form.shippingType=(this.form.shippingType).toString()
          if (this.form.storeId != null) {
            updateStore(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const storeIds = row.storeId || this.ids;
      this.$confirm('是否确认删除店铺管理编号为"' + storeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStore(storeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有店铺管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportStore(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>

    .avatar-uploader .el-upload {
       border: 1px dashed #d9d9d9;
       border-radius: 6px;
       cursor: pointer;
       position: relative;
       overflow: hidden;
     }
     .avatar-uploader .el-upload:hover {
       border-color: #409EFF;
     }

     .avatar-uploader-icon {
       font-size: 28px;
       color: #8c939d;
       width: 150px;
       height: 150px;
       line-height: 150px;
       text-align: center;
     }
</style>
